﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using XChip_Common;
using System.Threading;
using System.IO.Ports;
using SerialPortHelperLib;
using System.IO;
using DevExpress.LookAndFeel;
using System.Text.RegularExpressions;
using XChipTool.Enties;
using System.Runtime.InteropServices;
using System.Configuration;
using DevExpress.XtraBars.Navigation;
using DevExpress.Diagram.Core.Native.Ribbon;
using BinAnalysisHelp;
using XModem.library;
using Newtonsoft.Json;
using XChipTool.Full;
using System.Reflection;
using AdbService;

namespace XChipTool
{


    public partial class XChipForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {



        #region 全局变量
        /// <summary>
        /// 创建上下文同步
        /// </summary>
        //private SynchronizationContext context;
        public uint i2cmIndex = 0; //i2c打开的设备序号
        public bool m_open = false;  //i2c设备打开标志
        public bool IsI2C = false; //是否是i2c模式
        public uint i2cid = 0; //i2cid
        private SerialPort sPortTemp;
        private bool btnbool = true;
        public static bool isSecurity = true;
        //用于处理未安装vc库的弹窗
        private int Vcindex = 0;
        //private readonly xc128registerManager register = new xc128registerManager();
        private portconfigManager pcManager;
        //是否执行事件的标志，非人为触法，不要执行事件情况下
        private bool evenMask = false;
        private portconfig PCModel = new portconfig();
        /// <summary>
        /// 创建一个adb窗体
        /// </summary>
        private ADBForm adbForm;


        [DllImport("X64/XChipUSB_x64.dll", CallingConvention = CallingConvention.Cdecl)]
        public extern static IntPtr UsbControlInit();

        [DllImport("X64/XChipUSB_x64.dll", CallingConvention = CallingConvention.Cdecl)]
        public extern static IntPtr UsbOpenDevice();

        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private string USBItemIndex = string.Empty;



        //private AdbDeviceManager _adbManager;

      
        private void OpenCloesPort()
        {
            try
            {
                //if (!comBoxPorts.Text.ToLower().Contains("com"))
                //{
                //    return;
                //}
                //sPortTemp.PortName = comBoxPorts.Text;
                //sPortTemp.BaudRate = Convert.ToInt32(comBoxBaudRate.EditValue);
                sPortTemp.DataBits = 8;//int.Parse(comBoxDataBits.Text);
                sPortTemp.StopBits = System.IO.Ports.StopBits.One;
                sPortTemp.ReadTimeout = 1000;
                sPortTemp.WriteTimeout = 1000;
                sPortTemp.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), "Even"); //comBoxParity.EditValue.ToString()
                sPortTemp.DtrEnable = true;
                sPortTemp.RtsEnable = true;
                sPortTemp.Close();
                sPortTemp.Open();

                if (sPortTemp.IsOpen)
                {
                    //添加串口赋值过程
                    SetOpenSport();



                    //ARM 使能
                    uint recdata = 0;
                    var d = SerialSend.ReadRegister(0x80500000, sPortTemp);
                    var dd = SerialSend.ReadRegister(0x80500001, sPortTemp);
                    if (d != 0x51 || dd != 0x01)
                    {
                        setShowMsg("芯片ID有误！停止请求！");
                        sPortTemp.Close();
                        return;
                    }
                    #region 验证bin密码
                    var binH1 = SerialSend.ReadRegister(0x200018d0, sPortTemp).ToString("x2");
                    var binH2 = SerialSend.ReadRegister(0x200018d1, sPortTemp).ToString("x2");
                    var binH3 = SerialSend.ReadRegister(0x200018d2, sPortTemp).ToString("x2");
                    var binH4 = SerialSend.ReadRegister(0x200018d3, sPortTemp).ToString("x2");
                    if (SerialSend.ReadRegister(0x200018d4, sPortTemp).ToString("x2") == "00")
                    {

                    }
                    else
                    {
                        var temp1 = Convert.ToUInt32($"{binH1}{binH2}{binH3}{binH4}", 16);
                        var str = AppHelper.GetAppConfig("BinSecretKey");
                        var eee = AppHelper.XorNotEncryption(str);
                        if (eee != temp1)
                        {
                            sPortTemp.Close();
                            setShowMsg("请输入正确的Bin密钥！");
                            //DevExpress.XtraEditors.XtraMessageBox.Show("请输入正确的Bin密钥！");
                            return;
                        }
                    }
                    #endregion
                    recdata = (uint)recdata & (~0x0000000fU);//bit0-bit3写0
                    //SerialSend.WriteRegister(0x21, 0x80500200, recdata, sPortTemp);

                    //xChip_XModem.OpenPort(sPortTemp, comBoxBaudRate.EditValue.ToString(), comBoxPorts.Text);
                    //btnOpenPort.Text = "关闭";
                    //setButtonBackColor(Color.SeaGreen, btnOpenPort);

                    //检测isp_osd是否打开
                    SerialSend.isDebug = false;
                    uint temp = (uint)SerialSend.ReadRegister(0x80300000, sPortTemp);
                    SerialSend.isDebug = true;
                    evenMask = true;
                    check_IspOSD.Checked = (temp & 0x80) == 0x80;
                    evenMask = false;

                    #region 存下此时的波特率与串口
                    PCModel = pcManager.GetSingle(c => true);
                    if (null != PCModel)
                    {
                        portconfig model = new portconfig();
                        model.ID = PCModel.ID;
                        //model.PortName = comBoxPorts.EditValue.ToString();
                        //model.BaudRate = comBoxBaudRate.EditValue.ToString();

                        pcManager.Update(model);
                    }
                    else
                    {
                        portconfig model = new portconfig();
                        //model.PortName = comBoxPorts.EditValue.ToString();
                        //model.BaudRate = comBoxBaudRate.EditValue.ToString();

                        pcManager.Insert(model);
                    }
                    #endregion
                }
                //else
                //{
                //    //setButtonBackColor( btnOpenPort);
                //    //setButtonBackColor(Color.BlueViolet, btnOpenPort);
                //    //btnOpenPort.Text = "打开";
                //}
                //setButtonBackColor(btnOpenPort);

            }
            catch (Exception ex)
            {
                setShowMsg(ex.Message.ToString());
                //setButtonBackColor(btnOpenPort);
                //setButtonBackColor(Color.BlueViolet, btnOpenPort);
                sPortTemp.Close();
            }
        }


        string xc128head = string.Format("{0}\\Lib\\xc151_header", Application.StartupPath);
        string xc128setting = string.Format("{0}\\Lib\\xc151_setting", Application.StartupPath);
        string xcbin = string.Format("{0}\\Lib\\XChip_Bin", Application.StartupPath);
        //string SettingPath = $"{Application.StartupPath}\\Lib\\SettingPath";


        XChip_AE xChip_AE;
        XChip_AWB xChip_AWB;
        XChip_CMX xChip_CMX;
        XChip_DNR xChip_DNS;
        //XChip_DETAIL xChip_DETAIL;
        XChip_GAMMA xChip_GAMMA;
        XChip_SDE xChip_SDE;
        XChip_RegTable xChip_RegTable;
        XChip_LENC xChip_LENC;
        //XChip_DeriveOut xChip_DeriveOut;
        XChip_RegMapping xChip_RegMapping;
        XChip_Scene_Switch xChip_Scene_Switch;
        //XChip_SimpleUpdateIQ xChip_SimpleUpdateIQ;
        XChip_CRL xChip_CRL;
        XChip_CADJ_C xChip_CADJ;
        XChip_DNR_CAL xChip_DNR_CAL;
        XChip_DeriveNew xChip_DeriveNew;
        XChip_ToolBox xChip_ToolBox;
        XChip_Gpio xChip_Gpio;
        //XChip_CADJ_C xChip_CADJ_C;
        XChip_HDR xChip_HDR;
        XChip_Reg_Yde xChip_Reg_Yde;
        XChip_Reg_Ynr xChip_Reg_Ynr;
        XChip_Reg_Cfa xChip_Reg_Cfa;
        XChip_Reg_Snr xChip_Reg_Snr;
        XChip_Reg_FCC xChip_Reg_FCC;
        XChip_ToBin_Security xChip_ToBin_Security;
        XModemForm xChip_XModem;
        XChip_HDR_Ae xChip_HDR_Ae;
        XChip_HDR_GAMMA xChip_HDR_GAMMA;
        XChip_TveSizeReckon xChip_TveSizeReckon;
        XChip_Flash xChip_Flash;
        XChip_TopReg xChip_TopReg;
        XChip_AF xChip_af;
        XChip_Clock xChip_Clock;
        IntelligenceSettings xChip_Intelligence;


        public parameter_exportManager Pe_dal { get; set; }
        private addressregisterManager addressregisterBll { get; set; }
        private xc128registerManager RegisterDal { get; set; }
        private xc151registerManager Register151Dal { get; set; }
        private xcmainregisterManager XregitsterDal { get; set; }

        private parameter_export_patchManager Pe_patch_dal { get; set; }
        private parameter_export_sceneManager Pes_dal { get; set; }
        #endregion
        private bincurrencyManager Bincurrency_BLL { get; set; }
        private serialdataManager Serialdata_BLL { get; set; }

        /// <summary>
        /// 记录usb 是否打开的状态
        /// </summary>
        private bool IsUsbOpen { get; set; } = false;


        public XChipForm()
        {

            //System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

            //// 开始计时
            //stopwatch.Start();



            InitializeComponent();
            //// 停止计时
            //stopwatch.Stop();
            //this.Load += XChipForm_Load;
            //// 获取运行时间
            //TimeSpan elapsedTime = stopwatch.Elapsed;
            //var aa = $"运行时间：{elapsedTime}" ;
            //xChip_DeriveOut1.Pe_dal = new parameter_exportManager();
            //xChip_GAMMA1.gammaM = new gammahistoryManager();
            //xChip_RegTable2.RegisterDal = new xc128registerManager();
            //xChip_RegTable2.XregitsterDal = new xcmainregisterManager();
            //xChip_Security641.bindefault_BLL = new bindefaultManager();
            //xChip_Security641.bincurrency_BLL = new bincurrencyManager();
            //xChip_Security641.xc128_1bll = new xc151Manager();
            //xChip_Security641.serialdata_BLL = new serialdataManager();
            //xChip_Security641.control_BLL = new control_parameterManager();
            //xChip_Security641.Pe_dal = new parameter_exportManager();

            //xChip_Driving_11.bindefault_BLL = new bindefaultManager();
            //xChip_Driving_11.bincurrency_BLL = new bincurrencyManager();
            //xChip_Driving_11.xc128_1bll = new xc151Manager();
            //xChip_Driving_11.Pe_dal = new parameter_exportManager();
            //xChip_Driving_11.control_BLL = new control_parameterManager();
            //xChip_Driving_11.serialdata_BLL = new serialdataManager();

            //xChip_DeriveNew1.Pe_dal = new parameter_exportManager();
            //xChip_DeriveNew1.Pes_dal = new parameter_export_sceneManager();

            //xChip_SimpleUpdateIQ1.Pe_dal = new parameter_exportManager();   
            //xChip_CADJ1.Pe_dal = new parameter_exportManager();

            //发布正式版需要注释代码
            //xChip_CADJ_C2.SendSetClick += XChip_CADJ_C2_SendSetClick1;
        }
        private void ResetDockStyleOnAllControls(Control.ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                // 将Dock属性设置为None  
                control.Dock = DockStyle.None;

                // 如果控件有子控件，递归处理  
                if (control.HasChildren)
                {
                    ResetDockStyleOnAllControls(control.Controls);
                }
            }
        }
        #region 初始化文件
        private  void XChipForm_Load(object sender, EventArgs e)
        {
            //await AdbLogcatHelper.Instance.StartContinuousLogcatAsync();
            //logger.Debug("测试");
            //用于调试Bin按钮开关显示和隐藏
            if (ConfigurationManager.AppSettings["IsBin"] == "1")
            {
                BinBtn.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                BinBtn.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }

            //Task.Run(() => { AppHelper.ClearFileToPath(SettingPath, false); });
            switch (AppHelper.GetAppConfig("CutFun"))
            {
                case "0":

                    break;
                case "1":
                    barButtonItem21.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    break;
                case "2":
                    barButtonItem24.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    //barButtonItem23.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    break;
                default:
                    break;
            }

            #region 配置提示
            toolTipC.AutoPopDelay = 5000;
            toolTipC.InitialDelay = 0;
            toolTipC.ReshowDelay = 500;
            //toolTipC.SetToolTip(updateIqBtn, "批量更新setting区已导入文件的IQ");
            #endregion

            //默认收起菜单
            this.ribbonControl.Minimized = false;
            #region 基本操作选项卡
            //comBoxPorts.Properties.ValueMember = "ValueMember";
            //comBoxPorts.Properties.DisplayMember = "DisplayMember";
            //comBoxPorts.Properties.DataSource = XChip_Common.Port.GetSerialPorts();
            //comBoxPorts.ItemIndex = 0;


            //comBoxBaudRate.Properties.ValueMember = "ValueMember";
            //comBoxBaudRate.Properties.DisplayMember = "DisplayMember";
            //comBoxBaudRate.Properties.DataSource = XChip_Common.Port.GetRate();
            //comBoxBaudRate.ItemIndex = 4;

            #endregion
            //if (context == null)
            //{
            //    context = SynchronizationContext.Current;
            //}
            //setButtonBackColor(Color.BlueViolet, btnOpenPort);


            SerialSend.SendSerialSendClick += SerialSend_SendSerialSendClick;

            //btn_AE.PerformClick();//初始化AE界面
            //navigationFrame.SelectedPage = page_Xmodem;
            //navigationFrame.SelectedPage = page_CADJ;
            //navigationFrame.SelectedPage = Page_Cadj_C;
            //navigationFrame.SelectedPageIndex = 0;
            PagesLoad();
            if (GetConfigValue("IsI2C") == "1")
            {
                IsI2C = true;
            }
            else
            {
                IsI2C = false;
            }
            //if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            //{
            //    string exePath = AppDomain.CurrentDomain.BaseDirectory;
            //    string iconPath = System.IO.Path.Combine(exePath, "151ToolUSB.ico");
            //    Icon appIcon = new Icon(iconPath);
            //    this.Icon = appIcon;
            //    if (IsI2C)
            //    {
            //        portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalRight;Size16x16;Office2013";
            //        //PortControl.Hide();
            //        //UsbControl.Width = 0;
            //        //UsbControl.Hide();
            //        //PortControl.Width = 0;
            //        //I2cControl.Width = 167;
            //        int maxRetries = 5; // 设置最大重试次数  
            //        int retryCount = 0;
            //        while (retryCount < maxRetries)
            //        {
            //            // 检查文件是否存在且内容不为空  
            //            if (RefreshUsb())
            //            {
            //                Console.WriteLine("文件存在且不为空");
            //                break; // 文件已正确写入，退出循环  
            //            }
            //            // 等待一段时间再重试  
            //            Thread.Sleep(1000); // 2000毫秒 = 2秒  
            //            retryCount++;
            //        }
            //        isUsbmodeVisible(true);
            //    }
            //    else
            //    {
            //        portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalRight;Size16x16;Office2013";
            //        //PortControl.Hide();
            //        //PortControl.Width = 0;
            //        //I2cControl.Hide();
            //        //I2cControl.Width = 0;
            //        //UsbControl.Width = 167;
            //        int maxRetries = 5; // 设置最大重试次数  
            //        int retryCount = 0;
            //        while (retryCount < maxRetries)
            //        {
            //            // 检查文件是否存在且内容不为空  
            //            if (RefreshUsb())
            //            {
            //                Console.WriteLine("文件存在且不为空");
            //                break; // 文件已正确写入，退出循环  
            //            }
            //            // 等待一段时间再重试  
            //            Thread.Sleep(1000); // 2000毫秒 = 2秒  
            //            retryCount++;
            //        }
            //        isUsbmodeVisible(true);
            //    }

            //}
            //else
            if (GetConfigValue("IsSerial") == "ADB")
            {
                string exePath = AppDomain.CurrentDomain.BaseDirectory;
                string iconPath = System.IO.Path.Combine(exePath, "151Tool.ico");
                Icon appIcon = new Icon(iconPath);
                this.Icon = appIcon;
                portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalLeft;Size16x16;Office2013";
                AdbControl.Show();
                AdbControl.Width = 167;
                //PortControl.Hide();
                //UsbControl.Width = 0;
                //UsbControl.Hide();
                //PortControl.Width = 0;
                //I2cControl.Hide();
                //I2cControl.Width = 0;
                ShowADBFormAsync();

                barButtonItem21.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem15.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem42.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem16.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem38.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                barButtonItem39.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                btn_TVE_Reset.Visible = false;
                ribbonPageGroup2.Visible = false;
                Partition_check.Visible = false;
                sys_clk_txt.Visible = false;
                // 初始化ADB设备管理器 - 现在只需要一个按钮
                //_adbManager = new AdbDeviceManager(
                //    adbDevice,          // LookUpEdit控件
                //    adbIP,       // IP地址输入框
                //    btnAdb, // TCP/IP操作按钮（连接/断开）
                //    simpleButton20 //刷新按钮
                //);
            }
            //else
            //{
            //    string exePath = AppDomain.CurrentDomain.BaseDirectory;
                
            //    if (GetConfigValue("ismipiout") == "1")
            //    {
            //        string iconPath = System.IO.Path.Combine(exePath, "151Tool.ico");
            //        Icon appIcon = new Icon(iconPath);
            //        this.Icon = appIcon;
            //        portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalLeft;Size16x16;Office2013";
            //        //PortControl.Show();
            //        //PortControl.Width = 167;
            //        //I2cControl.Hide();
            //        //I2cControl.Width = 0;
            //        //UsbControl.Width = 0;
            //        isUsbmodeVisible(true);
            //        //groupControl2.Visible = false;
            //        barButtonItem43.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            //        BInIQ.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            //        barButtonItem49.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            //    }
            //    else
            //    {
            //        string iconPath = System.IO.Path.Combine(exePath, "151ToolTVE.ico");
            //        Icon appIcon = new Icon(iconPath);
            //        this.Icon = appIcon;
            //        portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalLeft;Size16x16;Office2013";
            //        //PortControl.Show();
            //        //PortControl.Width = 167;
            //        //I2cControl.Hide();
            //        //I2cControl.Width = 0;
            //        //UsbControl.Width = 0;
            //        isUsbmodeVisible(false);
            //    }
            //}
            ////ResetDockStyleOnAllControls(this.Controls);
        }



        /// <summary>
        /// 异步显示ADBForm
        /// </summary>
        private async void ShowADBFormAsync()
        {
            try
            {
                await Task.Run(() =>
                {
                    // 在后台线程创建窗体
                    ADBForm adbForm = new ADBForm();

                    // 在UI线程显示窗体
                    this.Invoke(new Action(() =>
                    {
                        adbForm.Show();
                        // 如果需要ADBForm随主窗体关闭而关闭，可以设置Owner
                        // adbForm.Owner = this;
                    }));
                });
            }
            catch (Exception ex)
            {
                // 记录错误，但不影响主界面启动
                Console.WriteLine($"打开ADBForm时出错: {ex.Message}");
            }
        }
        //是否是USB模式
        private void isUsbmodeVisible(bool isbool)
        {
            if (isbool)
            {
                barButtonItem21.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem15.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem42.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem16.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                barButtonItem38.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                barButtonItem39.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                btn_TVE_Reset.Visible = false;
                ribbonPageGroup2.Visible = false;
                Partition_check.Visible = false;
                sys_clk_txt.Visible = false;

                //updateIqBtn.Visible = false;
                //panelControl3.Visible = false;
                groupControl3.Size = new System.Drawing.Size(groupControl3.Width, groupControl3.Size.Height - 37);
                if (IsI2C)
                {
                    //groupControl2.Visible = false;
                    barButtonItem49.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    BInIQ.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    Sensor_i2cReadWrite.Visible = false;
                }
            }
            else
            {
                barButtonItem21.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem15.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem42.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem16.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                barButtonItem38.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                btn_TVE_Reset.Visible = true;
                ribbonPageGroup2.Visible = true;
                Partition_check.Visible = true;
                sys_clk_txt.Visible = true;

                //updateIqBtn.Visible = true;
                //panelControl3.Visible = true;
            }
            simpleButton17_Click(null, null);

        }
        private void PagesLoad()
        {

            sPortTemp = new SerialPort();
            //pcManager = new portconfigManager();
            Pe_dal = new parameter_exportManager();
            Pe_patch_dal = new parameter_export_patchManager();
            addressregisterBll = new addressregisterManager();
            RegisterDal = new xc128registerManager();
            Register151Dal = new xc151registerManager();
            XregitsterDal = new xcmainregisterManager();
            Pes_dal = new parameter_export_sceneManager();
            Bincurrency_BLL = new bincurrencyManager();
            Serialdata_BLL = new serialdataManager();
            pcManager = new portconfigManager();
            xChip_Intelligence = new IntelligenceSettings();

            serialPort1 = new SerialPortHelper();
            //发送使用的串口通讯
            serialPort1.BindSerialPortDataReceivedProcessEvent(new SerialPortHelper.DelegateSerialPortDataReceivedProcessEvent(SerialPortDataReceivedProcess1));
            serialPort1.BindSerialPortErrorEvent(new SerialPortHelper.DelegateSerialPortErrorEvent(SerialPortErrorProcess));
            serialPort1.SerialReceviedTimeInterval = 10; //接收数据时间
            serialPort1.SerialReceviedTimeInterval = 1;  //发送数据时间
                                                         //serialPort1.SPort.WriteTimeout = 3000;
                                                         //serialPort1.SPort.ReadTimeout = 3000;
            serialPort2 = new SerialPortHelper();
            //接收使用的串口通讯
            serialPort2.BindSerialPortDataReceivedProcessEvent(new SerialPortHelper.DelegateSerialPortDataReceivedProcessEvent(SerialPortDataReceivedProcess2));
            serialPort2.BindSerialPortErrorEvent(new SerialPortHelper.DelegateSerialPortErrorEvent(SerialPortErrorProcess));
            serialPort2.SerialReceviedTimeInterval = 1; //接收数据时间
            serialPort2.SerialReceviedTimeInterval = 1;  //发送数据时间


            this.splashScreenManager1.ShowWaitForm();
            NavigationPage page = new NavigationPage();
            Task.Run(() => {
                AppHelper.ClearFileToPath(xc128head, true); AppHelper.ClearFileToPath(xc128setting, true); AppHelper.ClearFileToPath(xcbin, true);
                if (GetConfigValue("IsSerial") == "TVE" && GetConfigValue("ismipiout") != "1")
                {
                    xChip_XModem = new XModemForm(sPortTemp);
                    xChip_XModem.Dock = DockStyle.Fill;
                    xChip_XModem.OpenPortButtonClick += XModemForm_OpenPortButtonClick;
                    //xChip_XModem.sPortTemp = sPortTemp;
                    page.Controls.Add(xChip_XModem);
                    page.Name = "page_XModem";
                    navigationFrame.Invoke(new Action(() => {
                        navigationFrame.Pages.Add(page);
                    }));
                    Thread.Sleep(10);
                }
                if (GetConfigValue("ismipiout") == "1")
                {
                    xChip_XModem = new XModemForm(sPortTemp);
                }
                //navigationFrame.SelectedPage = page;
                page = new NavigationPage();
                xChip_AE = XChip_AE.Instance(sPortTemp, addressregisterBll);
                xChip_AE.Dock = DockStyle.Fill;
                page.Controls.Add(xChip_AE);
                page.Name = "page_AE";
                navigationFrame.Invoke(new Action(() => {
                    //去除左上角图标
                    ShowIcon = false;

                    navigationFrame.Pages.Add(page);
                    navigationFrame.SelectedPage = page;
                }));
                #region 恢复上次选择的波特率         
                PCModel = pcManager.GetSingle(c => true);
                if (null != PCModel)
                {
                    int baudNo = XChip_Common.Port.GetRate().FindIndex(c => c.ValueMember == PCModel.BaudRate);
                    if (baudNo == -1)
                    {
                        //var ds = comBoxBaudRate.Properties.DataSource as List<Enties.TreeListValue>;
                        //ds.Add(new Enties.TreeListValue { DisplayMember = PCModel.BaudRate, ValueMember = PCModel.BaudRate });
                        //baudNo = ds.FindIndex(c => c.ValueMember == PCModel.BaudRate);
                    }
                    //comBoxBaudRate.Invoke(new Action(() =>
                    //{
                    //    comBoxBaudRate.ItemIndex = baudNo;
                    //}));
                }
                #endregion
            });





            this.splashScreenManager1.CloseWaitForm();
        }



        private void SerialSend_SendSerialSendClick(string msg)
        {
            setShowMsg(msg);
        }
        #endregion
        #region 打开串口

       
        #endregion

        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DeriveNew"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DeriveNew");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DeriveNew");
                //xChip_DeriveNew.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();

                xChip_DeriveNew = new XChip_DeriveNew(Pe_dal, Pes_dal);
                xChip_DeriveNew.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DeriveNew);
                page.Name = "page_DeriveNew";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }


            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 12;
            //navigationFrame.SelectedPage = page_DeriveNew;

        }

        #region 设置文本框

        public void setShowMsg(string msg)
        {
            if (chk_IsShowLog.Checked)
            {
                this.Invoke((EventHandler)(delegate
                {
                    if (memoEdit1.Text.Length > 20000)
                    {
                        memoEdit1.Text = "";
                    }
                    //追加的形式添加到文本框末端，并滚动到最后。     
                    this.memoEdit1.Text = string.Format("{0} \r\n {2} {1}", this.memoEdit1.Text, msg, "");
                    this.memoEdit1.SelectionStart = memoEdit1.Text.Length;
                    this.memoEdit1.ScrollToCaret();

                }));
            }
        }
        #endregion
        private void SetOpenSport()
        {
            if (null != xChip_AE) xChip_AE.sPortTemp = sPortTemp;
            if (null != xChip_AWB) xChip_AWB.sPortTemp = sPortTemp;
            if (null != xChip_CMX) xChip_CMX.sPortTemp = sPortTemp;
            if (null != xChip_DNS) xChip_DNS.sPortTemp = sPortTemp;
            //if (null != xChip_DETAIL) xChip_DETAIL.sPortTemp = sPortTemp;
            if (null != xChip_GAMMA) xChip_GAMMA.sPortTemp = sPortTemp;
            if (null != xChip_SDE) xChip_SDE.sPortTemp = sPortTemp;
            if (null != xChip_RegTable) xChip_RegTable.sPortTemp = sPortTemp;
            if (null != xChip_LENC) xChip_LENC.sPortTemp = sPortTemp;
            //if (null != xChip_DeriveOut) xChip_DeriveOut.sPortTemp = sPortTemp;
            if (null != xChip_Scene_Switch) xChip_Scene_Switch.sPortTemp = sPortTemp;
            //if (null != xChip_SimpleUpdateIQ) xChip_SimpleUpdateIQ.sPortTemp = sPortTemp;
            if (null != xChip_CRL) xChip_CRL.sPortTemp = sPortTemp;
            if (null != xChip_CADJ) xChip_CADJ.sPortTemp = sPortTemp;
            if (null != xChip_DNR_CAL) xChip_DNR_CAL.sPortTemp = sPortTemp;
            if (null != xChip_Gpio) xChip_Gpio.sPortTemp = sPortTemp;
            //if (null != xChip_CADJ_C) xChip_CADJ_C.sPortTemp = sPortTemp;
            if (null != xChip_HDR) xChip_HDR.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Yde) xChip_Reg_Yde.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Ynr) xChip_Reg_Ynr.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Cfa) xChip_Reg_Cfa.sPortTemp = sPortTemp;
            if (null != xChip_Reg_Snr) xChip_Reg_Snr.sPortTemp = sPortTemp;
            if (null != xChip_Reg_FCC) xChip_Reg_FCC.sPortTemp = sPortTemp;
            if (null != xChip_ToBin_Security) xChip_ToBin_Security.sPortTemp = sPortTemp;
            if (null != xChip_XModem) { xChip_XModem.sPortTemp = sPortTemp; xChip_XModem.IsUsbOpen = IsUsbOpen; }
            if (null != xChip_TopReg) { xChip_TopReg.sPortTemp = sPortTemp; xChip_TopReg.IsUsbOpen = IsUsbOpen; }
            if (null != xChip_Clock) { xChip_Clock.sPortTemp = sPortTemp; xChip_Clock.IsUsbOpen = IsUsbOpen; }
            if (null != xChip_TveSizeReckon) { xChip_TveSizeReckon.sPortTemp = sPortTemp; }
            if (null != xChip_Intelligence) { xChip_Intelligence.sPortTemp = sPortTemp; }
            
        }



        #region 切换页面的所有方法

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GAMMA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GAMMA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GAMMA");

                xChip_GAMMA.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_GAMMA = new XChip_GAMMA(sPortTemp, addressregisterBll);
                xChip_GAMMA.Dock = DockStyle.Fill;
                //xChip_GAMMA.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_GAMMA);
                page.Name = "page_GAMMA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }

            //SetOpenSport();
            //this.xChip_GAMMA1.gammaM = new gammahistoryManager();
            //navigationFrame.SelectedPageIndex =5;
            //officeNavigationBar.SelectedItem = navigationBarItem6;

        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_AWB"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AWB");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AWB");

                xChip_AWB.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_AWB = new XChip_AWB(sPortTemp, addressregisterBll);
                xChip_AWB.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_AWB);
                page.Name = "page_AWB";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 1;
            //officeNavigationBar.SelectedItem = navigationBarItem2;           
        }

        private void barButtonItem4_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CMX"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CMX");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CMX");

                xChip_CMX.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_CMX = new XChip_CMX(sPortTemp, addressregisterBll);
                xChip_CMX.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CMX);
                page.Name = "page_CMX";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 2;
            //officeNavigationBar.SelectedItem = navigationBarItem3;          
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR");

                xChip_DNS.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNS = new XChip_DNR(sPortTemp, addressregisterBll);
                xChip_DNS.Dock = DockStyle.Fill;
                xChip_DNS.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNS);
                page.Name = "page_DNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 3;
            //officeNavigationBar.SelectedItem = navigationBarItem4;            
        }
        private void btn_DNR_CAL_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR_CAL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR_CAL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR_CAL");

                xChip_DNR_CAL.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNR_CAL = new XChip_DNR_CAL(sPortTemp, addressregisterBll);
                xChip_DNR_CAL.Dock = DockStyle.Fill;
                xChip_DNR_CAL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNR_CAL);
                page.Name = "page_DNR_CAL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_DNR_CAL;       
        }

        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 7;
            //officeNavigationBar.SelectedItem = navigationBarItem8;

        }

        private void barButtonItem9_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SDE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SDE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SDE");

                xChip_SDE.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_SDE = new XChip_SDE(sPortTemp, addressregisterBll);
                xChip_SDE.Dock = DockStyle.Fill;
                xChip_SDE.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_SDE);
                page.Name = "page_SDE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 6;
            //officeNavigationBar.SelectedItem = navigationBarItem7;          
        }




        #endregion

        private void barButtonItem10_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //btn_Reg

            if (navigationFrame.Pages.Any(c => c.Caption == "page_Reg"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_Reg");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_Reg");

            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_RegTable = new XChip_RegTable(sPortTemp, Register151Dal);
                xChip_RegTable.Dock = DockStyle.Fill;
                page.Controls.Add(xChip_RegTable);
                page.Name = "page_Reg";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 8;

        }

        private void barButtonItem14_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (navigationFrame.Pages.Any(c => c.Caption == "page_AE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AE");

            }
            //else {
            //    NavigationPage page = new NavigationPage();
            //    xChip_AE = new XChipTool.XChip_AE();
            //    xChip_AE.Dock = DockStyle.Fill;
            //    xChip_AE.sPortTemp = sPortTemp;
            //    page.Controls.Add(xChip_AE);
            //    page.Name = "page_AE";
            //    navigationFrame.Pages.Add(page);
            //    navigationFrame.SelectedPage = page;
            //}

        }

        private void barButtonItem13_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 4;
            //officeNavigationBar.SelectedItem = navigationBarItem5;          
        }

        private void btn_ISP_Write_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "TVE")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            {


                if (!sPortTemp.IsOpen)//串口检测
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                    return;
                }
                uint reg_address = Convert.ToUInt32(textEdit1.Text.Replace(" ", ""), 16);


                uint reg_data = Convert.ToUInt32(textEdit2.Text, 16);

                SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);
            }
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                uint reg_address = Convert.ToUInt32(textEdit1.Text.Replace(" ", ""), 16);


                uint reg_data = Convert.ToUInt32(textEdit2.Text, 16);
                SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);
            }
        }

        private void btn_ISP_Read_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "TVE")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            {
                if (!sPortTemp.IsOpen)//串口检测
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                    return;
                }
                if (string.IsNullOrEmpty(textEdit1.Text)) { return; }
                textEdit2.Text = SerialSend.ReadRegister(Convert.ToUInt32((textEdit1.Text).Replace(" ", ""), 16), sPortTemp).ToString("X2");
            }

            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen && !m_open)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                textEdit2.Text = SerialSend.ReadRegister(Convert.ToUInt32((textEdit1.Text).Replace(" ", ""), 16), sPortTemp).ToString("X2");
            }
            if (GetConfigValue("IsSerial") == "ADB")
            {
                //if (_adbManager.CheckDeviceConnectionStatus())
                //{
                    //textEdit2.Text = _adbManager.ReadRegister((textEdit1.Text).Replace(" ", ""));
                //} 

            }

        }
        public static UInt32 addr;//全局变量
        /// <summary>
        /// isp 文件写
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_WirteFile_Click(object sender, EventArgs e)
        {
            if (m_open)
            {
                OpenFileDialog openFileDialog3 = new OpenFileDialog();
                openFileDialog3.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                if (openFileDialog3.ShowDialog() == DialogResult.OK)//用户是否选择确定
                {
                    string txt_str = String.Empty;
                    string[] ss;
                    // string line;
                    UInt32 reg_address;
                    UInt32 reg_data;
                    //UInt32 Value;
                    StreamReader f2 = new StreamReader(openFileDialog3.FileName, System.Text.Encoding.GetEncoding("gb2312"));//gb2312编码，为制定文件名初始化
                    //WaitBefore.Start("文件写", "正在加载中", 60);
                    //SerialSend.isDebug = false;
                    while (f2.Peek() > -1)
                    {
                        try
                        {
                            txt_str = f2.ReadLine().Trim();
                            //ss = txt_str.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
                            if (txt_str.Contains("//"))//去除注释
                            {
                                txt_str = txt_str.Remove(txt_str.IndexOf("//"));
                            }
                            txt_str = txt_str.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格
                            ss = txt_str.Split(',');
                            if (ss.Length > 2)
                            {
                                if (ss[0].Trim() == "0xfffd")
                                {
                                    addr = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 24;
                                }
                                else if (ss[0].Trim() == "0xfffe")
                                {
                                    //addr = 0x80000000;                                   
                                    addr = (addr & 0xff000000) + ((Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 16);
                                }
                                else if (ss[0].Trim() == "0xffff")
                                {
                                    uint t;
                                    t = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff);
                                    Thread.Sleep((int)(t));
                                }

                                else if (ss[0].Trim() == "0xf4f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xf5f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xf6f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xfff3")
                                {
                                    UInt16 chip_id;
                                    reg_address = 0x80500010;
                                    reg_data = 0;
                                    SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);
                                    //fb.ReadRegData(0x11, reg_address, ref reg_data, sPortTemp);
                                    chip_id = (UInt16)(reg_data >> 16);
                                    if (chip_id != Convert.ToUInt32(ss[1].Trim(), 16))
                                    {
                                        f2.Close();//释放系统资源
                                        f2.Dispose();
                                        DevExpress.XtraEditors.XtraMessageBox.Show("Chip ID don't match, Write stopped!");
                                        //MessageBox.Show("Chip ID don't match, Write stopped!");
                                        break;
                                    }

                                }
                                else
                                {

                                    reg_address = addr + (Convert.ToUInt32(ss[0].Trim(), 16) & 0xffff);

                                    reg_data = Convert.ToUInt32(ss[1].Trim(), 16);
                                    SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);

                                    Thread.Sleep(5);
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            //MessageBox.Show(ex.Message);
                        }
                    }
                    f2.Close();
                    f2.Dispose();
                    SerialSend.isDebug = true;
                    //WaitBefore.Close();
                    DevExpress.XtraEditors.XtraMessageBox.Show("完成");
                    //MessageBox.Show("完成");
                   
                    return;

                }
            }

            if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    WaitBefore.Close();
                    return;
                }
                OpenFileDialog openFileDialog = new OpenFileDialog();//将打开的地址给ofd
                openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                if (openFileDialog.ShowDialog() == DialogResult.OK)//用户是否选择确定
                {
                    bool t;
                    if (IntPtr.Size == 8)
                    {
                        t = XChipUSB.UsbRegisterWriteFile64(openFileDialog.FileName);
                    }
                    else
                    {
                        t = XChipUSB.UsbRegisterWriteFile86(openFileDialog.FileName);
                    }
                    if (t)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("USB写入完成！");
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show("USB写入失败！");
                    }
                }
                WaitBefore.Close();
                return;
            }

            if (!sPortTemp.IsOpen)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                WaitBefore.Close();
                return;
            }
            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;
            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);
            //Flash Mode
            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendEvent += setShowMsg;
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0, sPortTemp);


            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)//用户是否选择确定
            {
                try
                {
                    string txt_str = String.Empty;
                    string[] ss;
                    // string line;
                    UInt32 reg_address;
                    UInt32 reg_data;
                    //UInt32 Value;
                    StreamReader f2 = new StreamReader(openFileDialog1.FileName, System.Text.Encoding.GetEncoding("gb2312"));//gb2312编码，为制定文件名初始化
                    WaitBefore.Start("文件写", "正在加载中", 60);
                    //SerialSend.isDebug = false;
                    while (f2.Peek() > -1)
                    {
                        try
                        {
                            txt_str = f2.ReadLine().Trim();
                            //ss = txt_str.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
                            if (txt_str.Contains("//"))//去除注释
                            {
                                txt_str = txt_str.Remove(txt_str.IndexOf("//"));
                            }
                            txt_str = txt_str.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格
                            ss = txt_str.Split(',');
                            if (ss.Length > 2)
                            {
                                if (ss[0].Trim() == "0xfffd")
                                {
                                    addr = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 24;
                                }
                                else if (ss[0].Trim() == "0xfffe")
                                {
                                    //addr = 0x80000000;                                   
                                    addr = (addr & 0xff000000) + ((Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 16);
                                }
                                else if (ss[0].Trim() == "0xffff")
                                {
                                    uint t;
                                    t = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff);
                                    Thread.Sleep(1000);
                                }

                                else if (ss[0].Trim() == "0xf4f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xf5f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xf6f5")
                                {
                                    ;
                                }
                                else if (ss[0].Trim() == "0xfff3")
                                {
                                    UInt16 chip_id;
                                    reg_address = 0x80500010;
                                    reg_data = 0;
                                    fb.ReadRegData(0x11, reg_address, ref reg_data, sPortTemp);
                                    chip_id = (UInt16)(reg_data >> 16);
                                    if (chip_id != Convert.ToUInt32(ss[1].Trim(), 16))
                                    {
                                        f2.Close();//释放系统资源
                                        f2.Dispose();
                                        DevExpress.XtraEditors.XtraMessageBox.Show("Chip ID don't match, Write stopped!");
                                        //MessageBox.Show("Chip ID don't match, Write stopped!");
                                        break;
                                    }

                                }
                                else
                                {

                                    reg_address = addr + (Convert.ToUInt32(ss[0].Trim(), 16) & 0xffff);

                                    reg_data = Convert.ToUInt32(ss[1].Trim(), 16);
                                    SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);

                                    Thread.Sleep(5);
                                }

                            }
                        }
                        catch (Exception ex)
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                            //MessageBox.Show(ex.Message);
                        }
                    }
                    Application.DoEvents();
                    f2.Close();//释放系统资源
                    f2.Dispose();
                    WaitBefore.Close();
                    SerialSend.isDebug = true;
                    DevExpress.XtraEditors.XtraMessageBox.Show("完成");
                    //MessageBox.Show("完成");
                }

                catch (Exception ex)
                {
                    WaitBefore.Close();
                    SerialSend.isDebug = true;
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                    //MessageBox.Show(ex.Message);
                }
            }
        }
        /// <summary>
        /// 参数导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ParaExport_Click(object sender, EventArgs e)
        {

            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            XChip_ParameterExportOptions xpar = new XChip_ParameterExportOptions(sPortTemp);
            xpar.ShowDialog();
            //if (!sPortTemp.IsOpen)
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
            //    return;
            //}

            //SaveFileDialog sfd = new SaveFileDialog();
            ////设置文件类型 
            //sfd.Filter = "配置文件（*.txt）|*.txt";

            ////设置默认文件类型显示顺序 
            //sfd.FilterIndex = 1;

            ////保存对话框是否记忆上次打开的目录 
            //sfd.RestoreDirectory = true;
            //sfd.FileName = "IQ_Setting_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            //if (sfd.ShowDialog() == DialogResult.OK)
            //{
            //    SerialSend.isDebug = false;
            //    StringBuilder sb = new StringBuilder();
            //    sb.Append("// ");
            //    sb.Append("#region config xchip_IQ_regs =\n");
            //    sb.Append("{\n");
            //    sb.Append("//********** Step 10 IQ setting********************************//\n");
            //    //Pe_dal = new parameter_exportManager();
            //    if (null != Pe_dal)
            //    {
            //        WaitBefore.Start("参数导出", "正在加载中", 60);
            //        //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
            //        string sceneStr = string.Empty;
            //        string cutFun = AppHelper.GetAppConfig("CutFun");
            //        switch (cutFun)
            //        {
            //            case "0":
            //                sceneStr += "ALL";
            //                break;
            //            case "1"://安防 
            //                sceneStr += "安防";
            //                break;
            //            case "2"://车载  
            //                sceneStr += "行车";
            //                break;
            //            default:
            //                break;
            //        }
            //        if (cutFun != "0")
            //            sceneStr += (SerialSend.ReadRegister((0x80500241), sPortTemp) & 0x08) == 0x08 ? "3D" : "2D";
            //        var tempList = Pe_dal.GetListToExport(sceneStr);
            //        //var moduleList = SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1?tempList.Select(c => c.Module).Distinct() : tempList.Where(c => c.Module != "3D DNS" && c.Module != "AE_LFC").Select(c => c.Module).Distinct();//[ 7: 0]Psram_Check_Status;
            //        var moduleList = tempList.Select(c => c.Module).Distinct().ToList();
            //        if (moduleList.Contains(null))
            //        {
            //            WaitBefore.Close();
            //            XtraMessageBox.Show("参数导出寄存器表中存在Module为null的寄存器,无法继续", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //            return;
            //        }
            //        #region 白天寄存器
            //        //var Pe_patch_dal = new parameter_export_patchManager();
            //        //var patchList = Pe_patch_dal.GetList();
            //        var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
            //        foreach (var item in conditionList)
            //        {
            //            if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
            //            {
            //                foreach (var item2 in tempList.Where(c => c.ConditionAddr == item))
            //                {
            //                    item2.RelationAddr = null;
            //                }
            //                //patchList.RemoveAll(c => c.ConditionAddr == item);
            //            }
            //        }
            //        #endregion
            //        sb.Append("//IQ_Start\n");
            //        sb.Append("0xfffd,0x80,\n");
            //        sb.Append("//10.1 IQ_common");
            //        //if (SerialSend.ReadRegister((0x8014080b), sPortTemp) == 1)//[ 7: 0]Psram_Check_Status;
            //        //{
            //        //tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);

            //        foreach (var items in moduleList)
            //        {
            //            if (items.Contains("avg_size"))
            //                sb.Append("\n//10.2 IQ_oneself");
            //            sb.Append($"\n//{items}\n");
            //            foreach (var item in tempList.Where(c => c.Module == items).OrderBy(c => c.SortNum))
            //            {
            //                if (item.ReadAddr.Contains("089a"))
            //                {

            //                }
            //                try
            //                {
            //                    sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
            //                    sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
            //                    if (!string.IsNullOrEmpty(item.ReadAddr))
            //                    {
            //                        //if (patchList.Count != 0 && patchList.Select(c => c.ReadAddr).Contains(item.ReadAddr))
            //                        if (!string.IsNullOrEmpty(item.RelationAddr))
            //                        {
            //                            var regVal = SerialSend.ReadRegister((Convert.ToUInt32(item.RelationAddr.Trim(), 16)), sPortTemp);
            //                            //bool isbit7 = !string.IsNullOrEmpty(patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit) && patchList.Where(c => c.ReadAddr == item.ReadAddr).First().Bit == "&0x7f";
            //                            bool isbit7 = !string.IsNullOrEmpty(item.Bit) && item.Bit == "&0x7f";
            //                            sb.Append(isbit7 ? $",0x{(regVal & 0x7f).ToString("x2")}," : $",0x{regVal.ToString("x2")},");
            //                        }
            //                        else
            //                        {
            //                            sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
            //                        }
            //                    }
            //                    sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
            //                    sb.Append("\n");
            //                }
            //                catch (Exception ex)
            //                {
            //                    WaitBefore.Close();
            //                    setShowMsg(item.ReadAddr);
            //                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            //                    throw;
            //                }
            //            }
            //        }
            //        sb.Append("\n//IQ_End\n");
            //        sb.Append("}\n");
            //        System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
            //        WaitBefore.Close();
            //        DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            //    }
            //    SerialSend.isDebug = true;
            //}
        }

        /// <summary>
        /// 切换缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            //backBtn.LookAndFeel.SetSkinStyle("Office 2016 Colorful");
            //Uri = 'Forward' Backward "Office 2016 Colorful"
            if (panelControl1.Size.Width == 40)
            {

                backBtn.ImageOptions.ImageUri = new DevExpress.Utils.DxImageUri("Backward;Size16x16;Office2013");

                panelControl1.Size = new System.Drawing.Size(174, panelControl1.Size.Height);

                foreach (Control item in panelControl1.Controls)
                {
                    if (item is PanelControl)
                    {
                        item.Show();
                    }
                }
            }
            else
            {
                backBtn.ImageOptions.ImageUri = new DevExpress.Utils.DxImageUri("Forward;Size16x16;Office2013");
                panelControl1.Size = new System.Drawing.Size(40, panelControl1.Size.Height);
                foreach (Control item in panelControl1.Controls)
                {
                    if (item.Name == "topControl")
                    {
                        continue;
                    }
                    if (item is PanelControl)
                    {
                        item.Hide();
                    }
                }
            }

        }

        private void barButtonItem16_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (navigationFrame.Pages.Any(c => c.Caption == "page_XModem"))
            {
                xChip_XModem.sPortTemp = sPortTemp;
                xChip_XModem.IsUsbOpen = IsUsbOpen;
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_XModem");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_XModem");

                xChip_XModem.CalculationCrystalOscillator();
            }
            else
            {
                xChip_XModem.IsUsbOpen = IsUsbOpen;
            }
            if (btnbool)
            {

                btnbool = false;
            }

            SetOpenSport();
            USBSwitch();
            //navigationFrame.SelectedPage = page_Xmodem;
            ////officeNavigationBar.SelectedItem = navigationBarItem11;
            //xModemForm1.SendSetXModemClick += XModemForm1_SendSetXModemClick;
            //xModemForm1.SendChangeSysClk += XModemForm1_SendChangeSysClk; ;
        }

        private void XModemForm1_SendChangeSysClk()
        {
            if (sPortTemp.IsOpen)
            {

                SerialSend.WriteRegister(0x80500021, 0x08, sPortTemp);
                //Thread.Sleep(1000);
                //xModemForm1.CalculationCrystalOscillator();
                //Thread.Sleep(1000);
            }
        }

        private void barButtonItem17_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_LENC"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_LENC");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_LENC");

                //xChip_LENC.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_LENC = new XChip_LENC(sPortTemp, addressregisterBll, Pe_patch_dal, Pe_dal);
                xChip_LENC.Dock = DockStyle.Fill;
                //xChip_LENC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_LENC);
                page.Name = "page_LENC";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
        }

        private void barButtonItem18_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_RegMapping"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_RegMapping");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_RegMapping");

                //xChip_RegMapping.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_RegMapping = new XChip_RegMapping(addressregisterBll);
                xChip_RegMapping.Dock = DockStyle.Fill;
                //xChip_LENC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_RegMapping);
                page.Name = "page_RegMapping";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //xChip_RegMapping2.Addr_dal = new addressregisterManager();

            //navigationFrame.SelectedPageIndex = 12;
            //officeNavigationBar.SelectedItem = null;
        }

        private void simpleButton1_Click_2(object sender, EventArgs e)
        {
            memoEdit1.Text = string.Empty;
        }


        private void barButtonItem19_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SCENE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SCENE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SCENE");

                xChip_Scene_Switch.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Scene_Switch = new XChip_Scene_Switch(sPortTemp, addressregisterBll);
                xChip_Scene_Switch.Dock = DockStyle.Fill;
                xChip_Scene_Switch.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Scene_Switch);
                page.Name = "page_SCENE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 14;
            //officeNavigationBar.SelectedItem = null;
        }

      
        /// <summary>
        /// 体统版本号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem20_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //DevExpress.XtraEditors.XtraMessageBox.Show(System.Configuration.ConfigurationManager.AppSettings["VER"].Replace("\\r", "\r").Replace("\\n", "\n"), "Version", MessageBoxButtons.OK, MessageBoxIcon.Information);
            Version xpar = new Version();
            xpar.sPortTemp = sPortTemp;
            xpar.ShowDialog();

        }

       
        /// <summary>
        /// 快捷工具
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem22_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //navigationFrame.SelectedPageIndex = 16;
            //officeNavigationBar.SelectedItem = null;
        }

        private void ConsReadButton_Click(object sender, EventArgs e)
        {

            Thread thread = new Thread(c => {
                MethodInvoker methodInvoker = new MethodInvoker(ShowFormConsRead);
                BeginInvoke(methodInvoker);
            });
            thread.Start();

        }

        private void ShowFormConsRead()
        {
            Xchip_ConsReadWin xchip_ConsReadWin = Xchip_ConsReadWin.GetInstance(IsUsbOpen);
            Xchip_ConsReadWin ot = Xchip_ConsReadWin.GetInstance();
            ot.StartPosition = FormStartPosition.CenterScreen;
            ot.sPortTemp = sPortTemp;
            //ot.ShowDialog();
            ot.m_open = m_open;
            ot.Show();
            ot.Focus();

        }


        private void barButtonItem24_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 18;
            //officeNavigationBar.SelectedItem = null;
        }

        private void barButtonItem15_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //if (navigationFrame.Pages.Any(c => c.Caption == "page_ToBin_Security"))
            //{
            //    navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_ToBin_Security");

            //}
            //else
            //{

            //    this.splashScreenManager1.ShowWaitForm();
            //    NavigationPage page = new NavigationPage();

            //    xChip_ToBin_Security = new XChip_ToBin_Security(Bincurrency_BLL, Serialdata_BLL , true);
            //    xChip_ToBin_Security.Dock = DockStyle.Fill;
            //    page.Controls.Add(xChip_ToBin_Security);
            //    page.Name = "page_ToBin_Security";
            //    navigationFrame.Pages.Add(page);
            //    navigationFrame.SelectedPage = page;
            //    this.splashScreenManager1.CloseWaitForm();
            //}

            this.splashScreenManager1.ShowWaitForm();
            NavigationPage page = new NavigationPage();
            if (null != xChip_ToBin_Security)
            {
                xChip_ToBin_Security.isSecurity = true;
            }
            xChip_ToBin_Security = XChip_ToBin_Security.Instance(Bincurrency_BLL, Serialdata_BLL, sPortTemp, true);
            xChip_ToBin_Security.Dock = DockStyle.Fill;
            page.Controls.Add(xChip_ToBin_Security);
            page.Name = "page_ToBin_Security";
            navigationFrame.Pages.Add(page);
            navigationFrame.SelectedPage = page;
            this.splashScreenManager1.CloseWaitForm();
            //SetOpenSport();
            //xChip_ToBin_Security1.Bincurrency_BLL = new bincurrencyManager();
            //xChip_ToBin_Security1.Serialdata_BLL = new serialdataManager();
            //navigationFrame.SelectedPage = Page_SecurityBin;

            //officeNavigationBar.SelectedItem = null;
        }

        private void btn_CRL_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CRL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CRL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CRL");

                xChip_CRL.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CRL = new XChip_CRL(sPortTemp, addressregisterBll);
                xChip_CRL.Dock = DockStyle.Fill;
                xChip_CRL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CRL);
                page.Name = "page_CRL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CRL;
            //officeNavigationBar.SelectedItem = null;
        }

        private void btn_CADJ_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CADJ"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CADJ");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CADJ");

                xChip_CADJ.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CADJ = new XChip_CADJ_C(sPortTemp, addressregisterBll);
                xChip_CADJ.Dock = DockStyle.Fill;
                xChip_CADJ.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CADJ);
                page.Name = "page_CADJ";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CADJ;
            //officeNavigationBar.SelectedItem = null;
        }


        private void Sensor_i2cReadWrite_Click(object sender, EventArgs e)
        {
            SerialSend.WriteRegister(0x20000069, 0x00, sPortTemp);

            XChip_SensorI2cForm xchip_sensorI2cForm = XChip_SensorI2cForm.GetInstance(IsUsbOpen);
            xchip_sensorI2cForm.StartPosition = FormStartPosition.CenterScreen;
            xchip_sensorI2cForm.ClearEvent();
            xchip_sensorI2cForm.SendSensor_i2cClick += setShowMsg;
            xchip_sensorI2cForm.SPortTemp = sPortTemp;
            xchip_sensorI2cForm.Show();
            xchip_sensorI2cForm.Focus();
        }

       

        private void btn_FileCheck_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                var msg = FileHelper.CheckFiles(openFileDialog1.FileName);
                if (!string.IsNullOrEmpty(msg))
                {
                    if (msg.Length > 1000)
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show($"问题数据过多！已无法显示！请检查文件！");
                    }
                    else
                    {
                        DevExpress.XtraEditors.XtraMessageBox.Show(msg);
                    }
                }
                else
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("校验已完成！未检测出问题！");
                }
            }
        }

        private void btn_TVE_Reset_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //SerialSend.WriteRegister(0x80500039, 0x03, sPortTemp);
            //SerialSend.WriteRegister(0x8050001a, 0x01, sPortTemp);
            //SerialSend.WriteRegister(0x80500019, 0x80, sPortTemp);

            //SerialSend.WriteRegister(0x80500039, 0x00, sPortTemp);
            //SerialSend.WriteRegister(0x8050001a, 0x00, sPortTemp);
            //SerialSend.WriteRegister(0x80500019, 0x00, sPortTemp);
            SerialSend.WriteRegister(0x80500137, 0xab, sPortTemp);
        }

        private void check_IspOSD_CheckedChanged(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (evenMask)
                return;
            uint temp = (uint)SerialSend.ReadRegister(0x80300004, sPortTemp);
            if (check_IspOSD.Checked)
            {
                SerialSend.WriteRegister(0x80300004, temp | 0x80, sPortTemp);
            }
            else
            {
                SerialSend.WriteRegister(0x80300004, temp & 0x7f, sPortTemp);
            }
        }
      
        /// <summary>
        /// bin密钥设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XChip_BinPassWord binF = new XChip_BinPassWord();
            binF.StartPosition = FormStartPosition.CenterScreen;
            binF.ShowDialog();
        }

        private void barButtonItem3_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_ToolBox"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_ToolBox");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_ToolBox");

            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_ToolBox = new XChip_ToolBox();
                xChip_ToolBox.Dock = DockStyle.Fill;
                page.Controls.Add(xChip_ToolBox);
                page.Name = "page_ToolBox";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = page_ToolBox;
            //officeNavigationBar.SelectedItem = null;
        }

        private void gpioBtn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GPIO"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GPIO");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GPIO");

                xChip_Gpio.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_Gpio = new XChip_Gpio(sPortTemp, addressregisterBll);
                xChip_Gpio.Dock = DockStyle.Fill;
                xChip_Gpio.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Gpio);
                page.Name = "page_GPIO";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //navigationFrame.SelectedPage = page_Gpio;
        }

        private void barStaticItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            AppHelper.UpdateAppConfig("xcEdition", "1");
            //--------------重启软件 start---------------
            //开启新的实例
            System.Diagnostics.Process.Start(Application.ExecutablePath);
            //关闭当前实例
            System.Diagnostics.Process.GetCurrentProcess().Kill();
            //--------------重启软件 end----------------- 
        }

        private void barButtonItem4_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CADJ"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CADJ")
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CADJ");
                xChip_CADJ.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_CADJ = new XChip_CADJ_C(sPortTemp, addressregisterBll);
                xChip_CADJ.Dock = DockStyle.Fill;
                xChip_CADJ.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CADJ);
                page.Name = "page_CADJ";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = Page_Cadj_C;
        }
       

       
     
        private void barButtonItem4_ItemClick_2(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_HDR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_HDR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_HDR");
                xChip_HDR.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_HDR = XChip_HDR.Instance(sPortTemp, addressregisterBll);
                xChip_HDR.Dock = DockStyle.Fill;
                xChip_HDR.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_HDR);
                page.Name = "page_HDR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //SetOpenSport();
            //navigationFrame.SelectedPage = Page_Hdr;
        }

        private void barButtonItem5_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SNR");

                xChip_Reg_Snr.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Snr = new XChip_Reg_Snr(sPortTemp, addressregisterBll);
                xChip_Reg_Snr.Dock = DockStyle.Fill;
                xChip_Reg_Snr.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Snr);
                page.Name = "page_SNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Snr;
        }

        private void barButtonItem9_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CFA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CFA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CFA");

                xChip_Reg_Cfa.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Cfa = new XChip_Reg_Cfa(sPortTemp, addressregisterBll);
                xChip_Reg_Cfa.Dock = DockStyle.Fill;
                xChip_Reg_Cfa.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Cfa);
                page.Name = "page_CFA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Cfa;
        }

        private void barButtonItem14_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //navigationFrame.SelectedPage = Page_Cnr;
        }

        private void barButtonItem10_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YNR_CNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YNR_CNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YNR_CNR");

                xChip_Reg_Ynr.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Ynr = new XChip_Reg_Ynr(sPortTemp, addressregisterBll);
                xChip_Reg_Ynr.Dock = DockStyle.Fill;
                xChip_Reg_Ynr.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Ynr);
                page.Name = "page_YNR_CNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Ynr;
        }

        private void barButtonItem13_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YDE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YDE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YDE");

                xChip_Reg_Yde.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Yde = new XChip_Reg_Yde(sPortTemp, addressregisterBll);
                xChip_Reg_Yde.Dock = DockStyle.Fill;
                xChip_Reg_Yde.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Yde);
                page.Name = "page_YDE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Yde;
        }

        private void barButtonItem17_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_FCC"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_FCC");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_FCC");

                xChip_Reg_FCC.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_FCC = new XChip_Reg_FCC(sPortTemp, addressregisterBll);
                xChip_Reg_FCC.Dock = DockStyle.Fill;
                xChip_Reg_FCC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_FCC);
                page.Name = "page_FCC";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //navigationFrame.SelectedPage = Page_Fcc;
        }

        private void barButtonItem19_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Task.Factory.StartNew(() => {
                XChip_CameraControl xc_camera = new XChip_CameraControl();
                xc_camera.ShowDialog();
            });

        }
        /// <summary>
        /// bin解析测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem23_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            binTestForm bintestform = new binTestForm();
            bintestform.StartPosition = FormStartPosition.CenterParent;
            bintestform.ShowDialog();
        }
       

       
        private void barButtonItem27_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_LENC"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_LENC");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_LENC");

                //xChip_LENC.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_LENC = new XChip_LENC(sPortTemp, addressregisterBll, Pe_patch_dal, Pe_dal);
                xChip_LENC.Dock = DockStyle.Fill;
                //xChip_LENC.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_LENC);
                page.Name = "page_LENC";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem34_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CFA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CFA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CFA");

                xChip_Reg_Cfa.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Cfa = new XChip_Reg_Cfa(sPortTemp, addressregisterBll);
                xChip_Reg_Cfa.Dock = DockStyle.Fill;
                xChip_Reg_Cfa.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Cfa);
                page.Name = "page_CFA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Cfa;
        }

        private void barButtonItem26_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CMX"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CMX");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CMX");

                xChip_CMX.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_CMX = new XChip_CMX(sPortTemp, addressregisterBll);
                xChip_CMX.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CMX);
                page.Name = "page_CMX";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem25_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_AWB"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AWB");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AWB");

                xChip_AWB.sPortTemp = sPortTemp;

            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_AWB = new XChip_AWB(sPortTemp, addressregisterBll);
                xChip_AWB.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_AWB);
                page.Name = "page_AWB";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();

            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 1;
            //officeNavigationBar.SelectedItem = navigationBarItem2;   
        }

        private void barButtonItem28_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CADJ"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CADJ");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CADJ");

                xChip_CADJ.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CADJ = new XChip_CADJ_C(sPortTemp, addressregisterBll);
                xChip_CADJ.Dock = DockStyle.Fill;
                xChip_CADJ.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CADJ);
                page.Name = "page_CADJ";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CADJ;
            //officeNavigationBar.SelectedItem = null;
        }

        private void barButtonItem29_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (navigationFrame.Pages.Any(c => c.Caption == "page_AE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_AE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_AE");

            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem30_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GAMMA"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GAMMA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GAMMA");

                xChip_GAMMA.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_GAMMA = XChip_GAMMA.Instance(sPortTemp, addressregisterBll);
                xChip_GAMMA.Dock = DockStyle.Fill;
                //xChip_GAMMA.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_GAMMA);
                page.Name = "page_GAMMA";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            xChip_GAMMA.gammaM = new gammahistoryManager();
            //navigationFrame.SelectedPageIndex =5;
            //officeNavigationBar.SelectedItem = navigationBarItem6;

        }

        private void barButtonItem31_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_HDR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_HDR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_HDR");

                xChip_HDR.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_HDR = XChip_HDR.Instance(sPortTemp, addressregisterBll);
                xChip_HDR.Dock = DockStyle.Fill;
                xChip_HDR.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_HDR);
                page.Name = "page_HDR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = Page_Hdr;
        }

        private void barButtonItem32_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR");

                xChip_DNS.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNS = new XChip_DNR(sPortTemp, addressregisterBll);
                xChip_DNS.Dock = DockStyle.Fill;
                xChip_DNS.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNS);
                page.Name = "page_DNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem33_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_DNR_CAL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_DNR_CAL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_DNR_CAL");

                xChip_DNR_CAL.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_DNR_CAL = new XChip_DNR_CAL(sPortTemp, addressregisterBll);
                xChip_DNR_CAL.Dock = DockStyle.Fill;
                xChip_DNR_CAL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_DNR_CAL);
                page.Name = "page_DNR_CAL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_DNR_CAL;       
        }

        private void barButtonItem35_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YNR_CNR"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YNR_CNR");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YNR_CNR");

                xChip_Reg_Ynr.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Ynr = new XChip_Reg_Ynr(sPortTemp, addressregisterBll);
                xChip_Reg_Ynr.Dock = DockStyle.Fill;
                xChip_Reg_Ynr.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Ynr);
                page.Name = "page_YNR_CNR";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Ynr;
        }

        private void barButtonItem36_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_YDE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_YDE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_YDE");

                xChip_Reg_Yde.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Reg_Yde = new XChip_Reg_Yde(sPortTemp, addressregisterBll);
                xChip_Reg_Yde.Dock = DockStyle.Fill;
                xChip_Reg_Yde.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Reg_Yde);
                page.Name = "page_YDE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //navigationFrame.SelectedPage = Page_Yde;
        }

        private void barButtonItem37_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_SCENE"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_SCENE");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_SCENE");

                xChip_Scene_Switch.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Scene_Switch = new XChip_Scene_Switch(sPortTemp, addressregisterBll);
                xChip_Scene_Switch.Dock = DockStyle.Fill;
                xChip_Scene_Switch.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Scene_Switch);
                page.Name = "page_SCENE";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPageIndex = 14;
            //officeNavigationBar.SelectedItem = null;
        }

        private void barButtonItem38_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_GPIO"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GPIO");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_GPIO");

                xChip_Gpio.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_Gpio = new XChip_Gpio(sPortTemp, addressregisterBll);
                xChip_Gpio.Dock = DockStyle.Fill;
                xChip_Gpio.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Gpio);
                page.Name = "page_GPIO";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            USBSwitch();
            //navigationFrame.SelectedPage = page_Gpio;
        }

        private void barButtonItem39_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_CRL"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_CRL");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_CRL");

                xChip_CRL.sPortTemp = sPortTemp;
            }
            else
            {
                WaitBefore.Start("请耐心等待...", "正在努力工作中");
                NavigationPage page = new NavigationPage();
                xChip_CRL = new XChip_CRL(sPortTemp, addressregisterBll);
                xChip_CRL.Dock = DockStyle.Fill;
                xChip_CRL.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_CRL);
                page.Name = "page_CRL";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                WaitBefore.Close();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
            //navigationFrame.SelectedPage = page_CRL;
            //officeNavigationBar.SelectedItem = null;
        }
        /// <summary>
        /// 用于切换串口USB切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void portusbBtn_Click(object sender, EventArgs e)
        {
            //IsSerial
            //AlignVerticalRight;Size16x16;Office2013  

            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            //if (GetConfigValue("IsSerial") == "USB")
            //{
            //    portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalRight;Size16x16;Office2013";
            //    PortControl.Hide();
            //    PortControl.Width = 0;
            //    UsbControl.Width = 167;
            //    RefreshUsb();
            //}
            //else
            //{
            //    portusbBtn.ImageOptions.ImageUri.Uri = "AlignVerticalLeft;Size16x16;Office2013";
            //    PortControl.Show();
            //    PortControl.Width = 167;
            //    UsbControl.Width = 0;
            //}

            //XChip_AeTest();
            XChip_AeTest2();
        }
        private string GetConfigValue(string strKey)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var settings = configFile.AppSettings.Settings;

            return settings[strKey].Value;
        }
        /// <summary>
        /// 摄像头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton4_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() => {
                XChip_CameraControl xc_camera = new XChip_CameraControl();
                xc_camera.ShowDialog();
            });
        }
        /// <summary>
        /// 刷新设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUsbRefresh_Click(object sender, EventArgs e)
        {
            if (!RefreshUsb())
            {
                MessageBox.Show("未获取到USB设备信息");
            };
        }

        private bool RefreshUsb()
        {
            try
            {

                int num = 0;
                //var selIndex = usbDevice.ItemIndex;
                IntPtr devicebool;
                if (IntPtr.Size == 8)
                {
                    XChipUSB.UsbIniDevice64();
                    XChipUSB.UsbUpdateDevice64();
                    num = XChipUSB.UsbGetDeviceNum64();
                    devicebool = XChipUSB.UsbGetAllDeviceInfo64();
                }
                else
                {
                    XChipUSB.UsbIniDevice86();
                    XChipUSB.UsbUpdateDevice86();
                    num = XChipUSB.UsbGetDeviceNum86();
                    devicebool = XChipUSB.UsbGetAllDeviceInfo86();
                }

                DeviceInfo[] deviceInfoArray = new DeviceInfo[num];
                for (int i = 0; i < deviceInfoArray.Length; i++)
                {
                    DeviceInfo deviceInfo = new DeviceInfo();
                    var one = (i * 120) * 2 + (i * 8);
                    deviceInfo.DevicePath = Marshal.PtrToStringAnsi(devicebool + one, 120);
                    var two = (i * 120) * 2 + 120 + (i * 8);
                    deviceInfo.DeviceName = Marshal.PtrToStringAnsi(devicebool + two, 120);
                    var three = (i * 120) * 2 + 240 + (i * 8);
                    deviceInfo.PID = Marshal.PtrToStringAnsi(devicebool + three, 4); // 读取内存中的 uint 值  
                    var four = (i * 120) * 2 + 240 + 4 + (i * 8);
                    deviceInfo.VID = Marshal.PtrToStringAnsi(devicebool + four, 4); // 读取内存中的 uint 值  
                    deviceInfoArray[i] = deviceInfo; // 将复制的数据添加到数组中  
                }
                string usbPath = string.Empty;
                if (USBDeviceHelp.UsbDev.Count(c => c.IsOpen == true) > 0)
                {
                    usbPath = USBDeviceHelp.UsbDev.Find(c => c.IsOpen == true).DevicePath;
                }

                USBDeviceHelp.UsbDev.Clear();
                //List<Enties.TreeListValue> list = new List<Enties.TreeListValue>();
                for (int i = 0; i < deviceInfoArray.Count(); i++)
                {
                    if (string.IsNullOrEmpty(deviceInfoArray[i].PID) || string.IsNullOrEmpty(deviceInfoArray[i].VID) || deviceInfoArray[i].PID == "\0\0\0\0" || deviceInfoArray[i].VID == "\0\0\0\0")
                    {
                        continue;
                    }
                    if (!string.IsNullOrEmpty(usbPath) && deviceInfoArray[i].DevicePath == usbPath)
                    {
                        USBDeviceHelp.UsbDev.Add(new USBDeviceModel() { DeviceName = deviceInfoArray[i].DeviceName, PID = deviceInfoArray[i].PID, VID = deviceInfoArray[i].VID, DevicePath = deviceInfoArray[i].DevicePath, Index = i, IsOpen = true });

                    }
                    else
                    {
                        USBDeviceHelp.UsbDev.Add(new USBDeviceModel() { DeviceName = deviceInfoArray[i].DeviceName, PID = deviceInfoArray[i].PID, VID = deviceInfoArray[i].VID, DevicePath = deviceInfoArray[i].DevicePath, Index = i, IsOpen = false });

                    }
                    //list.Add(new Enties.TreeListValue { ValueMember = $"{i}", DisplayMember = deviceInfoArray[i].DeviceName });
                }
                //usbDevice.Properties.ValueMember = "DevicePath";
                //usbDevice.Properties.DisplayMember = "DeviceName";
                //usbDevice.Properties.DataSource = USBDeviceHelp.UsbDev;
                //if (USBDeviceHelp.UsbDev.Count(c => c.IsOpen == true) > 0)
                //{
                //    usbDevice.ItemIndex = USBDeviceHelp.UsbDev.FindIndex(c => c.IsOpen == true);

                //}
                //else
                //{
                //    usbDevice.ItemIndex = 0;
                //    USBDeviceHelp.UsbDev[0].IsOpen = true;
                //}

                if (USBDeviceHelp.UsbDev.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 打开Usb设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUsb_Click(object sender, EventArgs e)
        {

            //if (null == usbDevice || usbDevice.Text.ToString().Contains("请"))
            //{
            //    MessageBox.Show("请选择USB设备！"); return;
            //}
            ////RefreshUsb();

            //var index = USBDeviceHelp.UsbDev.FindIndex(c => c.DevicePath == USBItemIndex);
            //if (index != -1 && btnUsb.Text.Contains("打开"))
            //{


            //    if (IntPtr.Size == 8)
            //    {
            //        XChipUSB.UsbIniDevice64();
            //        XChipUSB.UsbUpdateDevice64();
            //        IsUsbOpen = XChipUSB.UsbSelectDevice64(index);
            //    }
            //    else
            //    {
            //        XChipUSB.UsbIniDevice86();
            //        XChipUSB.UsbUpdateDevice86();
            //        IsUsbOpen = XChipUSB.UsbSelectDevice86(index);
            //    }
            //    SerialPortHelperLib.SerialSend.IsUsbOpen = IsUsbOpen;
            //    USBSwitch();
            //    var d = SerialSend.ReadRegister(0x80500000, sPortTemp);
            //    var dd = SerialSend.ReadRegister(0x80500001, sPortTemp);

            //    if (d != 0x51 || dd != 0x01)
            //    {
            //        setShowMsg("芯片ID有误！停止请求！");
            //        IsUsbOpen = false;
            //        setButtonUsbBackColor(btnUsb, false);
            //        if (IntPtr.Size == 8)
            //        {
            //            XChipUSB.UsbUpdateDevice64();
            //            //var t = XChipUSB.UsbDestroyUSB64();
            //        }
            //        else
            //        {
            //            XChipUSB.UsbUpdateDevice86();
            //            //var t = XChipUSB.UsbDestroyUSB86();
            //        }
            //        USBDeviceHelp.UsbDev.ForEach(c =>
            //        {

            //            c.IsOpen = false;

            //        });
            //        IsUsbOpen = false;
            //        USBSwitch();
            //        return;
            //    }
            //    #region 验证bin密码
            //    var binH1 = SerialSend.ReadRegister(0x200018d0, sPortTemp).ToString("x2");
            //    var binH2 = SerialSend.ReadRegister(0x200018d1, sPortTemp).ToString("x2");
            //    var binH3 = SerialSend.ReadRegister(0x200018d2, sPortTemp).ToString("x2");
            //    var binH4 = SerialSend.ReadRegister(0x200018d3, sPortTemp).ToString("x2");
            //    if (SerialSend.ReadRegister(0x200018d4, sPortTemp).ToString("x2") == "00")
            //    {

            //    }
            //    else
            //    {
            //        var temp1 = Convert.ToUInt32($"{binH1}{binH2}{binH3}{binH4}", 16);
            //        var str = AppHelper.GetAppConfig("BinSecretKey");
            //        var eee = AppHelper.XorNotEncryption(str);
            //        if (eee != temp1)
            //        {
            //            IsUsbOpen = false;
            //            setButtonUsbBackColor(btnUsb, false);
            //            if (IntPtr.Size == 8)
            //            {
            //                XChipUSB.UsbUpdateDevice64();
            //                //var t = XChipUSB.UsbDestroyUSB64();
            //            }
            //            else
            //            {
            //                XChipUSB.UsbUpdateDevice86();
            //                //var t = XChipUSB.UsbDestroyUSB86();
            //            }
            //            USBDeviceHelp.UsbDev.ForEach(c =>
            //            {

            //                c.IsOpen = false;

            //            });
            //            IsUsbOpen = false;
            //            USBSwitch();
            //            setShowMsg("请输入正确的Bin密钥！");
            //            //DevExpress.XtraEditors.XtraMessageBox.Show("请输入正确的Bin密钥！");
            //            return;
            //        }
            //    }
            //    #endregion

            //    setButtonUsbBackColor(btnUsb, true);
            //    USBDeviceHelp.UsbDev.ForEach(c => {
            //        if (c.DevicePath == USBItemIndex)
            //        {
            //            c.IsOpen = true;
            //        }
            //    });
            //    //btnUsb.Text = "关闭";
            //    SetOpenSport();
            //}
            //else
            //{
            //    IsUsbOpen = false;
            //    setButtonUsbBackColor(btnUsb, false);
            //    if (IntPtr.Size == 8)
            //    {
            //        XChipUSB.UsbUpdateDevice64();
            //        //var t = XChipUSB.UsbDestroyUSB64();
            //    }
            //    else
            //    {
            //        XChipUSB.UsbUpdateDevice86();
            //        //var t = XChipUSB.UsbDestroyUSB86();
            //    }
            //    USBDeviceHelp.UsbDev.ForEach(c => {

            //        c.IsOpen = false;

            //    });
            //    USBSwitch();
            //    //btnUsb.Text = "打开";
            //}
        }

        private void btn_Reset_Chip_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                return;
            }
            if (IsUsbOpen)
            {
                SerialSend.WriteRegister(0x80500137, 0xce, sPortTemp);
            }
            else
            {
                SerialSend.WriteRegister(0x80500137, 0xd2, sPortTemp);
            }

        }

        //模拟单击事件
        private void XModemForm_OpenPortButtonClick(bool isbool)
        {
            //btnOpenPort.PerformClick();
            if (isbool)
            {
                //setButtonBackColor(btnOpenPort);
            }
            else
            {
                OpenCloesPort();
            }

        }

        private void simpleButton4_Click_1(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                return;
            }
            //XChip_GroupWrite configFile = new XChip_GroupWrite(sPortTemp);
            //configFile.StartPosition = FormStartPosition.CenterParent;
            //configFile.ShowDialog();


            XChip_GroupWrite xchip_groupWrite = XChip_GroupWrite.GetInstance(sPortTemp);
            xchip_groupWrite.StartPosition = FormStartPosition.CenterScreen;
            xchip_groupWrite.Show();
            xchip_groupWrite.Focus();

        }
      

        List<XmodemRequest> rxtemplists = new List<XmodemRequest>();
        private FlashBase fb;

        //定义SerialPortHelper类
        private SerialPortHelper serialPort1;
        private SerialPortHelper serialPort2;

        //爆序号
        private int PackageTemp = 0;
        //判断是c 还是nak
        private int useCRC = -1;
        private bool isFinish = false;
        public string SavePath;
        /// <summary>
        /// 导入bin
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton3_Click(object sender, EventArgs e)
        {
            try
            {
                WaitBefore.Start("请耐心等待...", "正在开启中");
                if ((GetConfigValue("IsSerial") == "USB" && IsUsbOpen) || GetConfigValue("IsI2C") == "1")
                {
                    uint temp0 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength, sPortTemp, true);
                    uint temp1 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 1, sPortTemp, true);
                    uint temp2 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 2, sPortTemp, true);
                    uint temp3 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 3, sPortTemp, true);

                    SavePath = string.Format("{0}\\Lib\\xc151_Bin\\Xchip_Output_{1}.bin", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmms"));

                    var binLength = Convert.ToUInt32($"{temp3.ToString("X2")}{temp2.ToString("X2")}{temp1.ToString("X2")}{temp0.ToString("X2")}", 16);
                    if (binLength == 0xFFFFFFFF)
                    {
                        WaitBefore.Close();
                        DevExpress.XtraEditors.XtraMessageBox.Show("bin文件长度读取失败！");
                        return;
                    }
                    if (IntPtr.Size == 8)
                    {
                        XChipUSB.UsbFlashQuickReadFile64(SavePath, 0x0, binLength);
                    }
                    else
                    {
                        XChipUSB.UsbFlashQuickReadFile86(SavePath, 0x0, binLength);
                    }
                    int maxRetries = 5; // 设置最大重试次数  
                    int retryCount = 0;
                    while (retryCount < maxRetries)
                    {
                        // 检查文件是否存在且内容不为空  
                        if (File.Exists(SavePath) && new FileInfo(SavePath).Length > 0)
                        {
                            Console.WriteLine("文件存在且不为空");
                            break; // 文件已正确写入，退出循环  
                        }
                        // 等待一段时间再重试  
                        Thread.Sleep(2000); // 2000毫秒 = 2秒  
                        retryCount++;
                    }

                    OpenBinParsing();
                    if (BinHelp.BinList.Count(c => !string.IsNullOrEmpty(c.note) && c.note.Contains("setting区1_31_") && !c.note.Contains("_en") && !c.module.Contains("Header")) <= 0)
                    {
                        WaitBefore.Close();
                        DevExpress.XtraEditors.XtraMessageBox.Show("不存在可以解析的配置文件！");
                        return;
                    }
                    if (BinHelp.usbList.Count <= 0)
                    {
                        WaitBefore.Close();
                        DevExpress.XtraEditors.XtraMessageBox.Show("无法解析Bin文件！请联系管理员！");
                        return;
                    }
                }
                if (GetConfigValue("IsSerial") == "TVE")
                {
                    //logger.Debug("开始Bin文件导出！");
                    if (!sPortTemp.IsOpen)
                    {
                        WaitBefore.Close();
                        DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                        return;
                    }
                    SavePath = string.Format("{0}\\Lib\\xc151_Bin\\Xchip_Output_{1}.bin", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmms"));
                    uint temp0 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength, sPortTemp);
                    uint temp1 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 1, sPortTemp);
                    uint temp2 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 2, sPortTemp);
                    uint temp3 = (uint)SerialSend.ReadRegister(BinHelp.BinToLength + 3, sPortTemp);

                    var binLength = Convert.ToInt32($"{temp3.ToString("X2")}{temp2.ToString("X2")}{temp1.ToString("X2")}{temp0.ToString("X2")}", 16);

                    var receiveTempCout = Math.Ceiling(binLength / 1024.0);

                    rxtemplists = new List<XmodemRequest>();
                    /*
                     //计算长度
                    //计算系统频率
                    当前写死 为了测试 后期可能是活动
                    */
                    double sys_clk = double.Parse(sys_clk_txt.Text);
                    //当前已经修改成获取选项
                    var list1 = new List<string>();
                    foreach (var item in RegisterSystemHelp.ArmList)
                    {
                        list1.Add(SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp).ToString("X2"));
                    }
                    var dou2 = RegisterSystemHelp.arm_clk(list1[0], list1[1], list1[2], list1[3], list1[4], list1[5]);

                    if (sys_clk != dou2)
                    {
                        sys_clk = dou2;
                    }
                    var fsysPath = string.Format("{0}\\Lib\\xc151_Bin\\FSys.txt", Application.StartupPath);
                    var list = SYSHelper.GetFSys(sys_clk, 8);
                    var list2 = SYSHelper.GetFsys_Bps(115200, sys_clk, 4);
                    //写入静态list集合中
                    SYSHelper.SetFsysBps(list);
                    SYSHelper.SetFsysSystem(list2);
                    //获取生成字符串
                    var str = SYSHelper.CreateFsys();
                    //写入文件
                    File.WriteAllText(fsysPath, str);
                    if (binLength == 0x0)
                    {
                        setShowMsg("监测->获取Bin长度地址为0");
                        logger.Debug("监测->获取Bin长度地址为0");
                        return;
                    }

                    var listbin = SYSHelper.GetUintToList(binLength, 8);
                    //更新长度 // 修改成接收
                    SYSHelper.SetTxFlashLength(listbin, ParaList.Tx_flash_1k);
                    SYSHelper.SetTxFlashEeprom(ParaList.Tx_flash_1k, false, false);
                    //SYSHelper.SetTxFlashLength(listbin, ParaList.Tx_flash_1k);
                    //SYSHelper.SetTxFlashEeprom(ParaList.Tx_flash_1k, false, eepromcheck.Checked);

                    var txPath = string.Format("{0}\\Lib\\xc151_Bin\\TxFlash1K.txt", Application.StartupPath);
                    var tStr = SYSHelper.CreateTxFlash1K();
                    File.WriteAllText(txPath, tStr);


                    //获取系统评率
                    RegisterFileWrite(fsysPath);//先发系统频率
                    setShowMsg("发系统频率配置文件写入完成！");
                    logger.Debug("发系统频率配置文件写入完成!");
                    RegisterFileWrite(txPath);//再发波特率
                    SetSelectedPortConfig(sPortTemp.PortName, false);
                    setShowMsg("发波特率配置文件写入完成！");
                    logger.Debug("发波特率配置文件写入完成！");
                    if (sPortTemp.IsOpen)
                    {
                        sPortTemp.Close();

                        //setButtonBackColor(btnOpenPort);
                    }
                    string msg = string.Empty;
                    serialPort2.OpenCom(out msg);
                    serialPort2.Write(new byte[] { 0x15 });
                    setShowMsg(msg);
                }
            }
            catch (Exception)
            {

            }
            finally
            {
                WaitBefore.Close();
                DevExpress.XtraEditors.XtraMessageBox.Show("开启成功");
            }



            //解析导出Bin文件


            //OpenFileDialog sfd = new OpenFileDialog();
            ////设置文件类型 
            //sfd.Filter = "导入BIN（*.bin）|*.bin";
            ////设置默认文件类型显示顺序 
            //sfd.FilterIndex = 1;
            ////保存对话框是否记忆上次打开的目录 
            //sfd.RestoreDirectory = true;
            //if (sfd.ShowDialog() != DialogResult.OK) return;
            //string foldPath = Path.GetDirectoryName(sfd.FileName);
            //AppHelper.UpdateAppConfig("Folder_Road_Force", foldPath);
            //List<BinBase> blist;
            /////读取文件全部内容
            //blist = BinHelp.BinToList(sfd.FileName);
            //int headKey = 0x368;
            ////headLength是包含crc校验的长度，xclist是不包含crc校验
            //int headLength = 0x320;
            ////获取存放的开始地址 计算结束地址  赋值类
            //var HeadStartAddr = Convert.ToUInt32("0x" + blist[headKey + 1].original.ToString("X2") + blist[headKey].original.ToString("X2"), 16);
            //var HeadEndAddr = HeadStartAddr + headLength;

            //xc151binparsingManager xcm = new xc151binparsingManager();
            //var xclist = xcm.GetList();
            //blist = BinHelp.BinBaseToNode(blist, xclist);

        }

        private void OpenBinParsing()
        {
            
            if (!string.IsNullOrEmpty(SavePath))
            {
                logger.Debug("开始文件解析");
                //xc151binparsingManager xcm = new xc151binparsingManager();
                //var xclist = xcm.GetList();
                xc151_exManager xcmex = new xc151_exManager();
                var xclist = JsonConvert.DeserializeObject<List<xc151binparsing>>(xcmex.GetListToXc151Binparsing()).OrderBy(c => c.Id).ToList();
                BinHelp.OpenBinFile(SavePath, xclist, IsUsbOpen);
                logger.Debug("结束文件解析");
            }
        }


        /// <summary>
        /// 寄存器文件写
        /// </summary>
        /// <param name="path"></param>
        private void RegisterFileWrite(string path)
        {
            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;
            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);
            fb = new FlashBase(sPortTemp);
            //fb.SendEvent += Fb_SendEvent;
            try
            {
                string txt_str = String.Empty;
                string[] ss;
                UInt32 reg_address;
                UInt32 reg_data;
                UInt32 Value;
                StreamReader f2 = new StreamReader(path, System.Text.Encoding.GetEncoding("gb2312"));//gb2312编码，为制定文件名初始化

                while (f2.Peek() > -1)
                {
                    txt_str = f2.ReadLine().Trim();
                    ss = txt_str.Split(',');
                    if (ss.Length >= 2)
                    {

                        if (ss[0].Trim() == "0xfffd")
                        {

                            addr = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 24;
                        }
                        else if (ss[0].Trim() == "0xfffe")
                        {

                            //addr = 0x80000000;
                            addr += (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 16;
                        }
                        else if (ss[0].Trim() == "0xffff")
                        {

                            uint t;
                            t = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff);
                            Thread.Sleep(1000);
                        }
                        else if (ss[0].Trim() == "0xfff3")
                        {

                            UInt16 chip_id;
                            reg_address = 0x80500010;
                            reg_data = 0;
                            fb.ReadRegDataARM(0x11, reg_address, ref reg_data, sPortTemp);
                            chip_id = (UInt16)(reg_data >> 16);
                            if (chip_id != Convert.ToUInt32(ss[1].Trim(), 16))
                            {
                                f2.Close();//释放系统资源
                                f2.Dispose();
                                setShowMsg("Chip ID don't match, Write stopped!");
                                break;
                            }

                        }
                        else
                        {

                            reg_address = addr + (Convert.ToUInt32(ss[0].Trim(), 16) & 0xffff);
                            reg_data = Convert.ToUInt32(ss[1].Trim(), 16);
                            int byte_sel = (int)(reg_address) & 0x3;
                            byte_sel = byte_sel * 8;

                            //int reg_data = Convert.ToUInt32(txtBoxRegData.Text, 16);
                            reg_data = reg_data & 0xff;
                            reg_data = reg_data << byte_sel;
                            Value = fb.SendRegDataARM(0x21, reg_address, reg_data, sPortTemp);

                            if (Value != 0x21)
                            {
                                f2.Close();//释放系统资源
                                f2.Dispose();
                                //setShowMsg("error ->!= 0x21");
                                break;
                            }
                        }
                    }

                }

                Application.DoEvents();
                f2.Close();//释放系统资源
                f2.Dispose();

            }
            catch (Exception ex)
            {
                //setShowMsg(msg);
                setShowMsg(ex.Message.ToString());
            }

        }


        private void barButtonItem21_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.splashScreenManager1.ShowWaitForm();
            NavigationPage page = new NavigationPage();
            if (null != xChip_ToBin_Security)
            {
                xChip_ToBin_Security.isSecurity = false;
            }
            xChip_ToBin_Security = XChip_ToBin_Security.Instance(Bincurrency_BLL, Serialdata_BLL, sPortTemp, false);

            xChip_ToBin_Security.Dock = DockStyle.Fill;
            page.Controls.Add(xChip_ToBin_Security);
            page.Name = "page_ToBin_Security";
            navigationFrame.Pages.Add(page);
            navigationFrame.SelectedPage = page;
            this.splashScreenManager1.CloseWaitForm();


            //if (navigationFrame.Pages.Any(c => c.Caption == "page_ToBin_Security"))
            //{
            //    navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_ToBin_Security");

            //}
            //else
            //{

            //    this.splashScreenManager1.ShowWaitForm();
            //    NavigationPage page = new NavigationPage();

            //    xChip_ToBin_Security = new XChip_ToBin_Security(Bincurrency_BLL, Serialdata_BLL, true);
            //    xChip_ToBin_Security.Dock = DockStyle.Fill;
            //    page.Controls.Add(xChip_ToBin_Security);
            //    page.Name = "page_ToBin_Security";
            //    navigationFrame.Pages.Add(page);
            //    navigationFrame.SelectedPage = page;
            //    this.splashScreenManager1.CloseWaitForm();
            //}

        }
        /// <summary>
        /// 刷新监测
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton5_Click(object sender, EventArgs e)
        {

            if (GetConfigValue("IsSerial") == "USB")
            {
                uint pVule = 0x0;
                uint pfps = 0x0;
                var isbool = false;
                if (GetConfigValue("IsI2C") == "1")
                {
                    pVule = (uint)SerialSend.ReadRegister(BinHelp.CurrentSize, sPortTemp);
                    pfps = (uint)SerialSend.ReadRegister(0x200065cc, sPortTemp);
                }
                else
                {
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead64(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead86(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                }
                //200065cc显示当前出图帧率
                var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  
                int fps = 0;
                if (pfps != 0)
                {
                    fps = (int)(10000000 / pfps);
                }

                //monitorLab.Text = $"出图尺寸:{chang} * {kuang} {fps}fps";
            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    //DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                uint temp = (uint)SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                //var aaa = FlashRead((FlashRead(Convert.ToUInt32("368", 16)) + temp * 4 + 0xd4) + 0x0c);
                if (null != BinHelp.lspList)
                {
                    var lspModel = BinHelp.lspList.Find(c => c.SettingHex == temp);
                    //monitorLab.Text = $"{lspModel.tName}-{lspModel.vName}";
                }
            }

        }

        private uint FlashRead(uint flash_address)
        {
            //Fb_SendEvent("Flash操作->读 开始执行\r\n");

            long test_value1 = (long)BaseRegisterMap.SPI_BASE_ADDR;

            uint test_value2 = (uint)SPIRegisterMap.SPI_FUNCTION_SELECT;
            uint FUNCT_SEL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_CONTROL;
            uint CONTROL_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_CONTROL;
            uint SHIFT_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD0;
            uint TXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_TXD1;
            uint TXD1_ADDR = (uint)(test_value1 + test_value2);


            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD0;
            uint RXD0_ADDR = (uint)(test_value1 + test_value2);

            test_value2 = (uint)SPIRegisterMap.SPI_SHIFT_RXD1;
            uint RXD1_ADDR = (uint)(test_value1 + test_value2);


            //uint flash_address = Convert.ToUInt32(txtBoxFlashAddress.Text, 16);

            uint spi_shift_cnt;
            uint spi_rxvld_cnt;
            uint senddata;
            uint recvdata = 0;
            uint op_code = 0x03;

            FlashBase fb = new FlashBase(sPortTemp);
            fb.SendRegDataARM(0x1, FUNCT_SEL_ADDR, 0x1, sPortTemp);
            //fb.SendEvent += Fb_SendEvent;
            Thread.Sleep(200);
            senddata = (((flash_address & 0xff) << 24) + ((flash_address & 0xff00) << 8) + ((flash_address & 0xff0000) >> 8) + op_code);
            fb.SendRegDataARM(0x1, TXD0_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);
            spi_shift_cnt = 64;
            spi_rxvld_cnt = 32;
            senddata = (3 << 16) + (spi_rxvld_cnt << 8) + (spi_shift_cnt << 0);
            fb.SendRegDataARM(0x1, SHIFT_ADDR, senddata, sPortTemp);
            Thread.Sleep(200);

            fb.ReadRegDataARM(0x11, RXD0_ADDR, ref recvdata, sPortTemp);
            //Fb_SendEvent("Flash操作->读 执行完成\r\n");
            return recvdata;

        }
        /// <summary>
        /// 配置串口
        /// </summary>
        /// <param name="isStopBits">Parity 是空校验 true </param>
        /// <param name="issend"> true 使用发送  false 使用接收</param>
        /// <param name="useBlock1K"> true 表示是1kxmodel  false还是 xmodel</param>
        void SetSelectedPortConfig(string Ports, bool issend, bool isStopBits = true, bool _useBlock1K = true)
        {
            if (issend)
            {
                serialPort1.ConfigSerialPort = new ConfigComType()
                {
                    //PortName = comBoxPorts.Text,
                    PortName = Ports,
                    BaudRate = 115200,//xmodem波特率定死成115200,需要改3个地方setSelectedPortConfig、ConfigSerialPort、comBoxFSys_EditValueChanged
                    //BaudRate = int.Parse(comBoxBaudRate.Text),
                    //DataBits = int.Parse(comBoxDataBits.Text),
                    DataBits = 8,
                    StopBits = SerialPortHelperLib.StopBits.One,
                    //Parity = isStopBits ? SerialPortHelperLib.Parity.None : (SerialPortHelperLib.Parity)Enum.Parse(typeof(SerialPortHelperLib.Parity), comBoxParity.EditValue.ToString()),
                    Parity = isStopBits ? SerialPortHelperLib.Parity.None : SerialPortHelperLib.Parity.Even,

                };
                ////初始化全局变量
                PackageTemp = 0;
                ////useBlock1K = comBoxAgreement.EditValue.ToString() == "0" ? true : false;
                useCRC = -1;
                serialPort1.SerialReceviedTimeInterval = 5;
                serialPort1.SerialWriteTimeInterval = 0;
                //useBlock1K = _useBlock1K;
            }
            else
            {
                serialPort2.ConfigSerialPort = new ConfigComType()
                {
                    //PortName = comBoxPorts.Text,
                    PortName = Ports,
                    BaudRate = 115200,//xmodem波特率定死成115200,需要改3个地方setSelectedPortConfig、ConfigSerialPort、comBoxFSys_EditValueChanged
                                      //BaudRate = int.Parse(comBoxBaudRate.Text),
                                      //DataBits = int.Parse(comBoxDataBits.Text),
                    DataBits = 8,
                    StopBits = SerialPortHelperLib.StopBits.One,
                    //Parity = isStopBits ? SerialPortHelperLib.Parity.None : (SerialPortHelperLib.Parity)Enum.Parse(typeof(SerialPortHelperLib.Parity), comBoxParity.EditValue.ToString()),
                    Parity = isStopBits ? SerialPortHelperLib.Parity.None : SerialPortHelperLib.Parity.Even,
                };
                ////初始化全局变量
                PackageTemp = 0;
                ////useBlock1K = comBoxAgreement.EditValue.ToString() == "0" ? true : false;
                useCRC = -1;
                serialPort2.SerialReceviedTimeInterval = 30;
                serialPort2.SerialWriteTimeInterval = 1;
                //useBlock1K = _useBlock1K;
                //设置线程传送长度
                if (_useBlock1K)
                {
                    serialPort2.SerialReceviedLengthMax = 1028;
                }
                else
                {
                    serialPort2.SerialReceviedLengthMax = 132;
                }
            }
        }

        /// <summary>
        /// 记录上次一次发送序号
        /// </summary>
        private int tempReceived = 0;
        /// <summary>
        /// 记录当接收长度超过255重新开始计数
        /// </summary>
        private int tempSize = 0;
        private void SerialPortDataReceivedProcess2(object sender, byte[] arrDataReceived)
        {
            this.Invoke(new Action(() =>
            {

                try
                {
                    if (arrDataReceived.Length != 1028)
                    {
                        if (arrDataReceived.First() == 04)//表示结束接收
                        {
                            serialPort2.Write(new byte[] { 0x06, 0x06, 0x06, 0x06 }); //告诉终端结束这次发送
                            Thread.Sleep(1000);
                            receivePath();
                            serialPort2.SPort.DiscardInBuffer();
                            serialPort2.SPort.DiscardOutBuffer();
                            string msg = "导出完成！";
                            setShowMsg(msg);
                            logger.Debug(msg);
                            serialPort2.CloseCom(out msg);
                            setShowMsg(msg);
                            logger.Debug(msg);
                            isFinish = true;
                        }
                        else
                        {
                            string msg = "->获取数据长度不够，重新获取！";
                            setShowMsg(string.Format(msg));
                            logger.Debug(msg);
                            serialPort2.CloseCom(out msg);
                            tempSize = 0;
                        }
                        return;
                    }

                    if (arrDataReceived.First() == 04)//表示结束接收
                    {
                        serialPort2.Write(new byte[] { 0x06, 0x06, 0x06, 0x06 }); //告诉终端结束这次发送
                                                                                  //休眠下 导入到文件
                        Thread.Sleep(1000);
                        receivePath();

                        serialPort2.SPort.DiscardInBuffer();
                        serialPort2.SPort.DiscardOutBuffer();
                        string msg = "导出完成！";
                        setShowMsg(msg);
                        logger.Debug(msg);
                        serialPort2.CloseCom(out msg);
                        setShowMsg(msg);
                        logger.Debug(msg);
                        isFinish = true;
                        return;
                    }
                    //接收数据业务处理部分
                    else if (arrDataReceived.First() == (2)) //如果是1k 等于2 如果是k 就是1 处理头部分文件
                    {
                        List<byte> tembyte = new List<byte>();
                        XmodemRequest xRequest = new XmodemRequest();
                        xRequest.ControlCharacter = arrDataReceived.First();
                        xRequest.PackageNo = arrDataReceived[1];
                        var tempIndex = Convert.ToInt32(xRequest.PackageNo) - 1; //接收第二位
                        xRequest.PackageInverseNo = arrDataReceived[2];

                        byte lastCrc;
                        //判断校验位

                        xRequest.DataList = arrDataReceived.Skip(3).Take(1024).ToList();
                        tembyte.AddRange(arrDataReceived.Skip(3).Take(1024));
                        xRequest.CheckBit = new byte[] { arrDataReceived.Skip(1027).Take(1).First() };
                        lastCrc = arrDataReceived.Skip(1027).Take(1).First(); //获取校验位

                        if (lastCrc != BitConverter.GetBytes(XModem.library.Port.GetCkSum(tembyte.ToArray()))[0]) //判断校验位是否正确
                        {
                            setShowMsg(string.Format("校验位不正确重新发送NAK"));
                            logger.Debug("校验位不正确重新发送NAK");
                            serialPort2.Write(new byte[] { 0x15 }); //重新NAk获取

                        }
                        else
                        {
                            serialPort2.Write(new byte[] { 0x06 }); //获取下一个
                            if (tempIndex != tempReceived)
                            {
                                tempSize++;
                            }

                            xRequest.No = tempSize;
                            setShowMsg(string.Format("->导出数据{0}包", tempSize));

                            rxtemplists.Add(xRequest);
                            tempReceived = tempIndex;
                        }

                    }
                    else if (arrDataReceived.First() == 24)
                    {
                        simpleButton4.Text = "导出";
                        string msg = "连接超时！";
                        setShowMsg(msg);
                        logger.Debug(msg);
                        serialPort2.CloseCom(out msg);
                        setShowMsg(msg);
                        logger.Debug(msg);
                    }
                    else
                    {
                        serialPort2.Write(new byte[] { 0x15 }); //重新NAk获取
                    }

                }
                catch (Exception ex)
                {
                    serialPort2.DiscardInBuffer();
                    string msg = "导出错误信息:";
                    setShowMsg(msg);
                    logger.Debug(msg);
                    serialPort2.CloseCom(out msg);
                    logger.Debug(msg);
                    setShowMsg(string.Format("导出错误信息：{0}", ex.Message.ToString()));
                    logger.Debug(string.Format("导出错误信息：{0}", ex.Message.ToString()));
                    tempSize = 0;
                }


            }));
        }


        /// <summary>
        /// 导出路径
        /// </summary>
        /// <param name="path"></param>
        private void receivePath()
        {
            //保存数据到路劲下
            //去除重复数据据
            rxtemplists = rxtemplists.Distinct(new XModemForm.ListByteComparer()).ToList();

            using (FileStream fs = new FileStream(SavePath, FileMode.Create))
            {
                using (BinaryWriter plik = new BinaryWriter(fs))
                {
                    //if (templists.Count>= receiveTempCout)
                    //{

                    var lastrx = rxtemplists.Last();
                    if (lastrx.DataList[0] == 0x1a && lastrx.DataList[1] == 0x0 && lastrx.DataList.Last() == 0x0)
                    {
                        rxtemplists.Remove(lastrx);
                    }

                    foreach (var item in rxtemplists)
                    {

                        foreach (var temD in item.DataList)
                        {

                            plik.Write(temD);
                        }
                    }

                }
            }
            tempSize = 0;
            Thread.Sleep(100);
            OpenBinParsing();
        }
        private void SerialPortDataReceivedProcess1(object sender, byte[] arrDataReceived)
        {
            this.Invoke(new Action(() =>
            {
                try
                {
                    setShowMsg(string.Format("->接收:{1}  烧入{0}次数。。。", PackageTemp, Convert.ToString(arrDataReceived[0], 16)));
                    //发送数据业务处理部分
                    switch (arrDataReceived[0])
                    {

                        case 0x43: //表示c
                            {
                                useCRC = 0;

                                serialPort1.WriteByte(XmodemData.xmodem1k_C[PackageTemp].ToArray());

                            }
                            break;
                        case 0x15: //表示nak
                            {
                                useCRC = 1;
                                if (PackageTemp > 0)
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_N[PackageTemp - 1].ToArray());
                                }
                                else
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_N[PackageTemp].ToArray());
                                }



                            }
                            break;
                        case 0x06: //表示ack
                            {

                                //if (true)
                                //{
                                if (PackageTemp > XmodemData.xmodem1k_C.Count - 1)
                                {
                                    //////发送取消命令 EOT 0x04
                                    serialPort1.Write(new byte[] { 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 });
                                    //////这里关闭通讯 切换回以前的串口通讯
                                    Thread.Sleep(1000); //由于在多线程中  如果需要关闭就需要添加延迟 然在关闭
                                    string msg = "烧写完成！";
                                    setShowMsg(msg);
                                    logger.Debug(msg);
                                    serialPort1.CloseCom(out msg);
                                    setShowMsg(msg);
                                    logger.Debug(msg);
                                    isFinish = true;
                                    serialPort1.DiscardInBuffer();
                                    DevExpress.XtraEditors.XtraMessageBox.Show("烧写完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                    ////打开串口
                                    //if (null != OpenPortButtonClick)
                                    //{
                                    //    OpenPortButtonClick();
                                    //}
                                    return;
                                }



                                if (useCRC == 0)
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_C[PackageTemp].ToArray());
                                }
                                if (useCRC == 1)
                                {
                                    serialPort1.WriteByte(XmodemData.xmodem1k_N[PackageTemp].ToArray());
                                }
                                PackageTemp++;
                            }
                            break;
                        case 0x18:
                            {
                                serialPort1.Write(new byte[] { 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 });
                                string msg = "烧写失败";
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.CloseCom(out msg);
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.DiscardInBuffer();
                            }
                            break;
                        default:
                            {
                                string msg = $"接收到错误指令{arrDataReceived[0]},无法继续，烧写失败";
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.CloseCom(out msg);
                                setShowMsg(msg);
                                logger.Debug(msg);
                                serialPort1.DiscardInBuffer();
                            }
                            break;
                    }

                }
                catch (Exception ex)
                {
                    string msg = "烧写失败";
                    serialPort1.DiscardInBuffer();
                    setShowMsg(msg);
                    logger.Debug(msg);
                    serialPort1.CloseCom(out msg);
                    setShowMsg(string.Format("烧写错误信息：{0}", ex.Message.ToString()));
                    logger.Debug(string.Format("烧写错误信息：{0}", ex.Message.ToString()));
                }
            }));
        }

        private void SerialPortErrorProcess(object sender, enumSerialError enumError, string strError)
        {
            this.Invoke(new Action(() =>
            {
                switch (enumError)
                {
                    case enumSerialError.LinkError:
                        string str = string.Empty;
                        if (!isFinish)
                        {
                            if (serialPort1.IsOpen)
                            {
                                serialPort1.CloseCom(out str);
                            }

                            if (serialPort2.IsOpen)
                            {
                                serialPort2.CloseCom(out str);
                            }


                        }
                        break;
                    case enumSerialError.WriteError:
                        //Fb_SendEvent(string.Format("发送错误：{0}", strError));
                        break;
                    case enumSerialError.ReceivedError:
                        //Fb_SendEvent(string.Format("接收错误：{0}", strError));
                        break;
                    default:
                        break;
                }
            }));
        }

        private void barButtonItem40_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            //xc151binparsingManager bll = new xc151binparsingManager();
            //var list = bll.GetList();
            // xc151Manager bll2 = new xc151Manager();
            // var list2 = bll2.GetList();
            // bindefaultManager bll3 = new bindefaultManager();
            // var list3 = bll3.GetList();

            //var str = Newtonsoft.Json.JsonConvert.SerializeObject(list);
            // var str2 = Newtonsoft.Json.JsonConvert.SerializeObject(list2);
            // var str3 = Newtonsoft.Json.JsonConvert.SerializeObject(list3);
            //xc151_exManager bll1 = new xc151_exManager();
            //bll1.Insert(new xc151_ex()
            //{
            //    Data = AESExample.EncryptString(str),
            //    Type = "xc151usbgraphics"
            //});
            // bll1.Insert(new xc151_ex()
            // {
            //     Data = AESExample.EncryptString(str2),
            //     Type = "xc151"
            // });
            // bll1.Insert(new xc151_ex()
            // {
            //     Data = AESExample.EncryptString(str3),
            //     Type = "bindefault"
            // });

            //var list4 = bll1.GetList();

            //foreach (var item in list4)
            //{
            //    switch (item.Type)
            //    {
            //        case "xc151binparsing":
            //            var str6 = AESExample.DecryptString(item.Data);
            //            break;
            //        case "xc151":
            //            var str7 = AESExample.DecryptString(item.Data);
            //            break;
            //        case "bindefault":
            //            var str8 = AESExample.DecryptString(item.Data);
            //            break;
            //        case "xc151usbgraphics":
            //            var str9 = AESExample.DecryptString(item.Data);
            //            if (str9 == str) {

            //            }
            //            break;
            //        default:
            //            break;
            //    }
            //}
            XChip_CToCode xchic = new XChip_CToCode();
            xchic.StartPosition = FormStartPosition.CenterScreen;
            xchic.ShowDialog();

        }

        private void USBSwitch()
        {
            if (null != xChip_AE) xChip_AE.IsUsbOpen = IsUsbOpen;
            if (null != xChip_AWB) xChip_AWB.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CMX) xChip_CMX.IsUsbOpen = IsUsbOpen;
            if (null != xChip_DNS) xChip_DNS.IsUsbOpen = IsUsbOpen;
            //if (null != xChip_DETAIL) xChip_DETAIL.sPortTemp = sPortTemp;
            if (null != xChip_GAMMA) xChip_GAMMA.IsUsbOpen = IsUsbOpen;
            if (null != xChip_SDE) xChip_SDE.IsUsbOpen = IsUsbOpen;
            if (null != xChip_LENC) xChip_LENC.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Scene_Switch) xChip_Scene_Switch.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CRL) xChip_CRL.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CADJ) xChip_CADJ.IsUsbOpen = IsUsbOpen;
            if (null != xChip_DNR_CAL) xChip_DNR_CAL.IsUsbOpen = IsUsbOpen;
            //if (null != xChip_Gpio) xChip_Gpio.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR) xChip_HDR.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR_Ae) xChip_HDR_Ae.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR_GAMMA) xChip_HDR_GAMMA.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Yde) xChip_Reg_Yde.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Ynr) xChip_Reg_Ynr.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Cfa) xChip_Reg_Cfa.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Reg_Snr) xChip_Reg_Snr.IsUsbOpen = IsUsbOpen;
            if (null != xChip_CADJ) xChip_CADJ.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Gpio) xChip_Gpio.IsUsbOpen = IsUsbOpen;
            if (null != xChip_XModem) xChip_XModem.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Flash) xChip_Flash.IsUsbOpen = IsUsbOpen;
            if (null != xChip_TopReg) xChip_TopReg.IsUsbOpen = IsUsbOpen;
            if (null != xChip_RegTable) xChip_RegTable.IsUsbOpen = IsUsbOpen;
            //if (null != xChip_Reg_FCC) xChip_Reg_FCC.IsUsbOpen = IsUsbOpen;
            if (null != xChip_af) xChip_af.IsUsbOpen = IsUsbOpen;
            if (null != xChip_Clock) xChip_Clock.IsUsbOpen = IsUsbOpen;

            if (null != xChip_Intelligence) { xChip_Intelligence.IsUsbOpen = IsUsbOpen; }
            SerialSend.IsUsbOpen = IsUsbOpen;

            if (null != xChip_AE) xChip_AE.m_open = m_open;
            if (null != xChip_AWB) xChip_AWB.m_open = m_open;
            if (null != xChip_CMX) xChip_CMX.m_open = m_open;
            if (null != xChip_DNS) xChip_DNS.m_open = m_open;
            //if (null != xChip_DETAIL) xChip_DETAIL.sPortTemp = sPortTemp;
            if (null != xChip_GAMMA) xChip_GAMMA.m_open = m_open;
            if (null != xChip_SDE) xChip_SDE.m_open = m_open;
            if (null != xChip_LENC) xChip_LENC.m_open = m_open;
            if (null != xChip_Scene_Switch) xChip_Scene_Switch.m_open = m_open;
            if (null != xChip_CRL) xChip_CRL.m_open = m_open;
            if (null != xChip_CADJ) xChip_CADJ.m_open = m_open;
            if (null != xChip_DNR_CAL) xChip_DNR_CAL.m_open = m_open;
            //if (null != xChip_Gpio) xChip_Gpio.IsUsbOpen = IsUsbOpen;
            if (null != xChip_HDR) xChip_HDR.m_open = m_open;
            if (null != xChip_HDR_Ae) xChip_HDR_Ae.m_open = m_open;
            if (null != xChip_HDR_GAMMA) xChip_HDR_GAMMA.m_open = m_open;
            if (null != xChip_Reg_Yde) xChip_Reg_Yde.m_open = m_open;
            if (null != xChip_Reg_Ynr) xChip_Reg_Ynr.m_open = m_open;
            if (null != xChip_Reg_Cfa) xChip_Reg_Cfa.m_open = m_open;
            if (null != xChip_Reg_Snr) xChip_Reg_Snr.m_open = m_open;
            if (null != xChip_CADJ) xChip_CADJ.m_open = m_open;
            if (null != xChip_Gpio) xChip_Gpio.m_open = m_open;
            //if (null != xChip_XModem) xChip_XModem.m_open = m_open;
            //if (null != xChip_Flash) xChip_Flash.m_open = m_open;
            //if (null != xChip_Reg_FCC) xChip_Reg_FCC.IsUsbOpen = IsUsbOpen;
            if (null != xChip_TopReg) xChip_TopReg.m_open = m_open;
            if (null != xChip_HDR_Ae) xChip_HDR_Ae.m_open = m_open;
            if (null != xChip_af) xChip_af.m_open = m_open;
            if (null != xChip_Clock) xChip_Clock.m_open = m_open;
            SerialSend.m_open = m_open;
        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            //var ty= Regex.Replace(textEdit1.Text, ".{4}", "$0");
            // textEdit1.Text = ty;
        }

        private void barButtonItem42_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            BinIqEffectCopy bintestform = new BinIqEffectCopy();
            bintestform.StartPosition = FormStartPosition.CenterParent;
            bintestform.ShowDialog();
        }

        private void simpleButton12_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "TVE")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalLeft"))
            {
                if (!sPortTemp.IsOpen)//串口检测
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                    return;
                }

                var m_nFollowArea0 = SerialSend.ReadRegister(0x200014c0, sPortTemp);
                var m_nFollowArea1 = SerialSend.ReadRegister(0x200014c1, sPortTemp);
                var m_nFollowArea2 = SerialSend.ReadRegister(0x200014c2, sPortTemp);
                var m_nFollowArea3 = SerialSend.ReadRegister(0x200014c3, sPortTemp);
                textEdit3.Text = (m_nFollowArea3 << 24 | m_nFollowArea2 << 16 | m_nFollowArea1 << 8 | m_nFollowArea0).ToString("X8");
            }

            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            //if (portusbBtn.ImageOptions.ImageUri.Uri.Contains("AlignVerticalRight"))
            {
                if (!IsUsbOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("USB未打开");
                    return;
                }
                var m_nFollowArea0 = SerialSend.ReadRegister(0x200014c0, sPortTemp);
                var m_nFollowArea1 = SerialSend.ReadRegister(0x200014c1, sPortTemp);
                var m_nFollowArea2 = SerialSend.ReadRegister(0x200014c2, sPortTemp);
                var m_nFollowArea3 = SerialSend.ReadRegister(0x200014c3, sPortTemp);
                textEdit3.Text = (m_nFollowArea3 << 24 | m_nFollowArea2 << 16 | m_nFollowArea1 << 8 | m_nFollowArea0).ToString("X8");
            }
        }

        private void simpleButton13_Click(object sender, EventArgs e)
        {
            if (null == BinHelp.lspList)
            {
                OpenBinParsing();
            }
            if (null != BinHelp.lspList)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();//将打开的地址给ofd
                openFileDialog.Filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*";
                if (openFileDialog.ShowDialog() == DialogResult.OK)//用户是否选择确定
                {
                    try
                    {
                        string txt_str = String.Empty;
                        string[] ss;
                        // string line;
                        UInt32 reg_address;
                        UInt32 reg_data;
                        //UInt32 Value;
                        StreamReader f2 = new StreamReader(openFileDialog.FileName, System.Text.Encoding.GetEncoding("gb2312"));//gb2312编码，为制定文件名初始化
                        WaitBefore.Start("文件写", "正在加载中", 60);
                        //SerialSend.isDebug = false;
                        while (f2.Peek() > -1)
                        {
                            try
                            {
                                txt_str = f2.ReadLine().Trim();
                                //ss = txt_str.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);
                                if (txt_str.Contains("//"))//去除注释
                                {
                                    txt_str = txt_str.Remove(txt_str.IndexOf("//"));
                                }
                                txt_str = txt_str.Replace('，', ',').Replace(" ", "");//全换成英文逗号，去掉空格
                                ss = txt_str.Split(',');
                                if (ss.Length > 2)
                                {
                                    if (ss[0].Trim() == "0xfffd")
                                    {
                                        addr = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 24;
                                    }
                                    else if (ss[0].Trim() == "0xfffe")
                                    {
                                        //addr = 0x80000000;                                   
                                        addr = (addr & 0xff000000) + ((Convert.ToUInt32(ss[1].Trim(), 16) & 0xff) << 16);
                                    }
                                    else if (ss[0].Trim() == "0xffff")
                                    {
                                        uint t;
                                        t = (Convert.ToUInt32(ss[1].Trim(), 16) & 0xff);
                                        Thread.Sleep(1000);
                                    }

                                    else if (ss[0].Trim() == "0xf4f5")
                                    {
                                        ;
                                    }
                                    else if (ss[0].Trim() == "0xf5f5")
                                    {
                                        ;
                                    }
                                    else if (ss[0].Trim() == "0xf6f5")
                                    {
                                        ;
                                    }
                                    else if (ss[0].Trim() == "0xfff3")
                                    {
                                        UInt16 chip_id;
                                        reg_address = 0x80500010;
                                        reg_data = 0;
                                        fb.ReadRegData(0x11, reg_address, ref reg_data, sPortTemp);
                                        chip_id = (UInt16)(reg_data >> 16);
                                        if (chip_id != Convert.ToUInt32(ss[1].Trim(), 16))
                                        {
                                            f2.Close();//释放系统资源
                                            f2.Dispose();
                                            DevExpress.XtraEditors.XtraMessageBox.Show("Chip ID don't match, Write stopped!");
                                            //MessageBox.Show("Chip ID don't match, Write stopped!");
                                            break;
                                        }

                                    }
                                    else
                                    {

                                        reg_address = addr + (Convert.ToUInt32(ss[0].Trim(), 16) & 0xffff);

                                        reg_data = Convert.ToUInt32(ss[1].Trim(), 16);
                                        //编写Bin更新数据
                                        var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                                        BinHelp.SetBinUpdateData(ref BinHelp.BinList, reg_address.ToString("X2"), reg_data.ToString("X"), (uint)temp);
                                        //SerialSend.WriteRegister(reg_address, reg_data, sPortTemp);

                                        Thread.Sleep(5);
                                    }

                                }
                            }
                            catch (Exception ex)
                            {
                                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                                //MessageBox.Show(ex.Message);
                            }
                        }
                        Application.DoEvents();
                        f2.Close();//释放系统资源
                        f2.Dispose();
                        WaitBefore.Close();
                        SerialSend.isDebug = true;
                        DevExpress.XtraEditors.XtraMessageBox.Show("完成");
                        //MessageBox.Show("完成");
                    }

                    catch (Exception ex)
                    {
                        WaitBefore.Close();
                        SerialSend.isDebug = true;
                        DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
                        //MessageBox.Show(ex.Message);
                    }
                }

            }


        }

        private void barButtonItem42_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_TveSizeReckon"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_TveSizeReckon");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_TveSizeReckon");

                //xChip_DeriveNew.sPortTemp = sPortTemp;
                xChip_TveSizeReckon.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();

                xChip_TveSizeReckon = new XChip_TveSizeReckon(sPortTemp);
                xChip_TveSizeReckon.Dock = DockStyle.Fill;
                //xChip_AWB.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_TveSizeReckon);
                page.Name = "page_TveSizeReckon";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }

        }

        private void barButtonItem2_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string directoryPath = Application.StartupPath + @"\DB\";
            string wordFilePath = "";
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                wordFilePath = Path.Combine(directoryPath, "XChipTool_Usb_ISP3.0芯片调试软件用户手册.doc");
            }
            else
            {
                wordFilePath = Path.Combine(directoryPath, "XChipTool_Tve_ISP3.0芯片调试软件用户手册.docx");
            }


            System.Diagnostics.Process.Start("explorer.exe", wordFilePath);
        }

        private void simpleButton14_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                var binlistTempusb = BinHelp.BinList;

                if (null == binlistTempusb || binlistTempusb.Count == 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无数据，请先下载！");
                    return;
                }
                SaveFileDialog sfd = new SaveFileDialog();
                //设置文件类型 
                sfd.Filter = "BIN文件（*.bin）|*.bin";
                //设置默认文件类型显示顺序 
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录 
                sfd.RestoreDirectory = true;
                //设置文件名
                sfd.FileName = "XChipNewbin_" + DateTime.Now.ToString("yyyyMMddHHmms");
                var Save_BIN_Output_File_FileName_Path = string.Empty;

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    Save_BIN_Output_File_FileName_Path = sfd.FileName.ToString();
                    //var hex = AppHelper.StringToUTF8(System.IO.Path.GetFileNameWithoutExtension(Save_BIN_Output_File_FileName_Path));
                    //if (!BinHelp.SetBinNameUpdateData(ref BinHelp.BinList, hex))
                    //{
                    //    DevExpress.XtraEditors.XtraMessageBox.Show("修改bin名称失败请检查");
                    //    return;
                    //}
                    BinHelp.BinOutFile(Save_BIN_Output_File_FileName_Path, binlistTempusb);
                    DevExpress.XtraEditors.XtraMessageBox.Show("导出完成");
                }

            }
            else if (GetConfigValue("IsSerial") == "ADB")
            {
                //_adbManager.StartLogcat();
            }
            else
            {
                BinHelp.IsPartition = Partition_check.Checked;
                //根据 分段发送测试
                var binlistTemp = BinHelp.GetUpdateIndex();
                if (null == binlistTemp || binlistTemp.Count == 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("无数据，请先下载！");
                    return;
                }
                SaveFileDialog sfd = new SaveFileDialog();
                //设置文件类型 
                sfd.Filter = "BIN文件（*.bin）|*.bin";
                //设置默认文件类型显示顺序 
                sfd.FilterIndex = 1;
                //保存对话框是否记忆上次打开的目录 
                sfd.RestoreDirectory = true;
                //设置文件名
                sfd.FileName = "XChipNewbin_" + DateTime.Now.ToString("yyyyMMddHHmms");
                var Save_BIN_Output_File_FileName_Path = string.Empty;

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    Save_BIN_Output_File_FileName_Path = sfd.FileName.ToString();
                    BinHelp.BinOutFile(Save_BIN_Output_File_FileName_Path, binlistTemp);
                    DevExpress.XtraEditors.XtraMessageBox.Show("导出完成");
                }

            }
        }

        private void simpleButton15_Click(object sender, EventArgs e)
        {
            //if (!sPortTemp.IsOpen)//串口检测 
            //{
            //    DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
            //    return;
            //}
            //USB是2000f28
            int aaa = 0x20000f28;
            List<byte> hexData = new List<byte>();
            for (int i = aaa; i < aaa + 40; i++)
            {
                hexData.Add((byte)SerialSend.ReadRegister((ulong)i, sPortTemp));
            }
            string asciiString = Encoding.ASCII.GetString(hexData.ToArray());
            DevExpress.XtraEditors.XtraMessageBox.Show("当前固件版本:" + asciiString);
        }


        
        private void XChip_AeTest2()
        {
            /*
            
            */

            List<ISPReg> regList = new List<ISPReg>();

            regList.Add(new ISPReg() { addr = 0x20000040, value = 0x0 });
            regList.Add(new ISPReg() { addr = 0x20000064, value = 0x0 });
            regList.Add(new ISPReg() { addr = 0x20000065, value = 0x0 });

            //regList.Add(new ISPReg() { addr = 0x80500020, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C78, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C79, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7A, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7B, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7C, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7D, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7E, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C7F, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C80, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C81, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C82, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C83, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C84, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C85, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C86, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C87, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C88, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C89, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8A, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8B, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8C, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8D, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8E, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C8F, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C90, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C91, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C92, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000C93, value = 0x40 });

            var isbool = true;
            int g = 0;

            while (isbool)
            {
                logger.Info($"调用次数 ------->{g}------->");
                try
                {
                    g++;
                    foreach (var item in regList)
                    {
                        item.value = (uint)new Random().Next(15);

                        bool issbool;
                        if (IntPtr.Size == 8)
                        {
                            issbool = XChipUSB.UsbRegisterWrite64((uint)item.addr, (uint)item.value, false);
                            SerialSend.Sendser("W:0x" + item.addr.ToString("X2"), item.value.ToString("X2") + ",状态：" + issbool);
                        }
                        //SerialSend.WriteRegister(item.addr, item.value, sPortTemp);
                    }

                    List<ISPReg> regListTemp = new List<ISPReg>();

                    foreach (var item in regList)
                    {
                        uint pVule = 0x0;
                        var issbool = false;
                        if (IntPtr.Size == 8)
                        {
                            issbool = XChipUSB.UsbRegisterRead64(item.addr, ref pVule, true);
                            SerialSend.Sendser("R:0x" + (item.addr).ToString("X2"), pVule.ToString("X2") + ",状态：" + issbool);


                        }

                        regListTemp.Add(new ISPReg() { addr = item.addr, value = (uint)pVule });
                    }

                    for (int i = 0; i < regList.Count; i++)
                    {


                        if (regListTemp.Find(c => c.addr == regList[i].addr).value == regList[i].value)
                        {
                            continue;
                        }
                        else
                        {
                            logger.Info($"测试出现错误 原始地址：{regList[i].addr.ToString("X")}原始值:{regList[i].value.ToString("X")}   错误值:{regListTemp.Find(c => c.addr == regList[i].addr).value.ToString("X")}");
                            isbool = false;
                        }
                    }

                }
                catch (Exception ex)
                {
                    logger.Info(ex.Message.ToString());
                    isbool = false;
                }

            }


        }


        private void XChip_RegTest()
        {
            /*
            目标：1. 测试修改寄存器写入读写时间后   是数据是否正常 
            目的：寄存器读写存在一个20毫秒的延迟时间，缩短这个延迟时间到1毫秒，看数据是否正常
            步骤： 1.定义一堆地址数据 2.写入数据 3.读取数据  4.校验数据
            
            */
            List<ISPReg> regList = new List<ISPReg>();

            regList.Add(new ISPReg() { addr = 0x80500050, value = 0x44 });
            regList.Add(new ISPReg() { addr = 0x80500051, value = 0x39 });
            regList.Add(new ISPReg() { addr = 0x80500052, value = 0x82 });
            regList.Add(new ISPReg() { addr = 0x80500053, value = 0x40 });

            //regList.Add(new ISPReg() { addr = 0x80500020, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000108, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000109, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010a, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010b, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010c, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010d, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010e, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x2000010f, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000110, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000111, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000112, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000113, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000114, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000115, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000116, value = 0x40 });
            regList.Add(new ISPReg() { addr = 0x20000117, value = 0x40 });

            var isbool = true;
            int g = 0;

            while (isbool)
            {
                logger.Info($"调用次数 ------->{g}------->");
                try
                {
                    g++;
                    foreach (var item in regList)
                    {
                        item.value = (uint)new Random().Next(15);
                        SerialSend.WriteRegister(item.addr, item.value, sPortTemp);
                    }

                    List<ISPReg> regListTemp = new List<ISPReg>();

                    foreach (var item in regList)
                    {
                        regListTemp.Add(new ISPReg() { addr = item.addr, value = (uint)SerialSend.ReadRegister(item.addr, sPortTemp) });
                    }

                    for (int i = 0; i < regList.Count; i++)
                    {


                        if (regListTemp.Find(c => c.addr == regList[i].addr).value == regList[i].value)
                        {
                            continue;
                        }
                        else
                        {
                            logger.Info($"测试出现错误 原始地址：{regList[i].addr.ToString("X")}原始值:{regList[i].value.ToString("X")}   错误值:{regListTemp.Find(c => c.addr == regList[i].addr).value.ToString("X")}");
                            isbool = false;
                        }
                    }

                }
                catch (Exception ex)
                {
                    logger.Info(ex.Message.ToString());
                    isbool = false;
                }

            }



        }
      
        
        
        /// <summary>
        /// 关闭软件需要释放USB接口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void XChipForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //if (GetConfigValue("IsSerial") == "USB")
            //{
            //    if (IntPtr.Size == 8)
            //    {
            //        //XChipUSB.UsbUpdateDevice64();
            //        XChipUSB.UsbDestroyUSB64();
            //    }
            //    else
            //    {
            //        //XChipUSB.UsbUpdateDevice86();
            //        XChipUSB.UsbDestroyUSB86();
            //    }
            //}
            if (GetConfigValue("IsSerial") == "ADB")
            {
                //AdbProcessManager.KillAllAdbProcesses();
            }
            //await AdbLogcatHelper.Instance.StopAsync();
            //AdbLogcatHelper.Instance.Dispose();
        }

        private void barButtonItem43_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_Flash"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_Flash");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_Flash");

                xChip_Flash.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Flash = XChip_Flash.Instance(sPortTemp);
                xChip_Flash.Dock = DockStyle.Fill;
                //xChip_GAMMA.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_Flash);
                page.Name = "page_Flash";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

       
        private void simpleButton17_Click(object sender, EventArgs e)
        {
            if (GetConfigValue("IsSerial") == "USB" || GetConfigValue("IsI2C") == "1")
            {
                uint pVule = 0x0;
                uint pfps = 0x0;
                var isbool = false;
                if (GetConfigValue("IsI2C") == "1")
                {
                    //pVule = (uint)SerialSend.ReadRegister(BinHelp.CurrentSize, sPortTemp);
                    //pfps = (uint)SerialSend.ReadRegister(0x200065cc, sPortTemp);
                }
                else
                {
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead64(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        isbool = XChipUSB.UsbRegisterRead86(0x200065cc, ref pfps, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                }
                //200065cc显示当前出图帧率
                var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  
                int fps = 0;
                if (pfps != 0)
                {
                    fps = (int)(10000000 / pfps);
                }

                //monitorLab.Text = $"{chang} * {kuang} {fps}fps";
            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    //DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                uint temp = (uint)SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                //var aaa = FlashRead((FlashRead(Convert.ToUInt32("368", 16)) + temp * 4 + 0xd4) + 0x0c);
                if (null != BinHelp.lspList)
                {
                    var lspModel = BinHelp.lspList.Find(c => c.SettingHex == temp);
                    //monitorLab.Text = $"{lspModel.tName}-{lspModel.vName}";
                }
            }
        }

        private void simpleButton18_Click(object sender, EventArgs e)
        {
            XChip_TopReg xchip_ConsReadWin = XChip_TopReg.GetInstance(sPortTemp, addressregisterBll);
            XChip_TopReg ot = XChip_TopReg.GetInstance();
            ot.StartPosition = FormStartPosition.CenterScreen;
            ot.sPortTemp = sPortTemp;
            USBSwitch();
            ot.IsUsbOpen = IsUsbOpen;
            //ot.ShowDialog();
            ot.m_open = m_open;
            ot.Show();
            ot.Focus();
        }

        private void BInIQ_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            BinIqEffectCopy bintestform = new BinIqEffectCopy();
            bintestform.StartPosition = FormStartPosition.CenterParent;
            bintestform.ShowDialog();
        }

      
        delegate void SetTextCallback(string text);
      
      

        private void barButtonItem44_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            if (navigationFrame.Pages.Any(c => c.Caption == "page_af"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_af");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_af");

                //xChip_af.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_af = XChip_AF.Instance(sPortTemp, addressregisterBll);
                xChip_af.Dock = DockStyle.Fill;
                xChip_af.sPortTemp = sPortTemp;
                page.Controls.Add(xChip_af);
                page.Name = "page_af";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
        }

        private void barButtonItem45_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (navigationFrame.Pages.Any(c => c.Caption == "page_Clock"))
            {
                //navigationFrame.SelectedPageIndex = navigationFrame.Pages.FindIndex(c => c.Caption == "page_GAMMA");
                navigationFrame.SelectedPage = (INavigationPage)navigationFrame.Pages.FindFirst(c => c.Caption == "page_Clock");

                xChip_Clock.sPortTemp = sPortTemp;
            }
            else
            {
                this.splashScreenManager1.ShowWaitForm();
                NavigationPage page = new NavigationPage();
                xChip_Clock = XChip_Clock.Instance(sPortTemp);
                xChip_Clock.Dock = DockStyle.Fill;
                page.Controls.Add(xChip_Clock);
                page.Name = "page_Clock";
                navigationFrame.Pages.Add(page);
                navigationFrame.SelectedPage = page;
                this.splashScreenManager1.CloseWaitForm();
            }
            //对USB开关赋值
            USBSwitch();
            //SetOpenSport();
        }
        /// <summary>
        /// 最新版本自动推送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem46_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (GetConfigValue("IsSerial") == "TVE")
            {
                AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/tve/New/auto.xml");
            }
            else
            {
                AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/usb/New/auto.xml");
            }
               
        }
        /// <summary>
        ///  前一稳定版
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem47_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AutoUpdaterDotNET.AutoUpdater.InstalledVersion = new System.Version("0.0.0.0");
            if (GetConfigValue("IsSerial") == "TVE")
            {
                AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/tve/Old/auto.xml");
            }
            else
            {
                AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/usb/Old/auto.xml");
            }   
            
        }
        /// <summary>
        ///  前二稳定版
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem48_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AutoUpdaterDotNET.AutoUpdater.InstalledVersion = new System.Version("0.0.0.0");
            if (GetConfigValue("IsSerial") == "TVE")
            {
                AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/tve/Last/auto.xml");
            }
            else
            {
                AutoUpdatorHelper.Start("http://49.232.124.138/xchiptool-isp3/usb/Last/auto.xml");
            } 
            
        }

        private void barButtonItem49_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
            xChip_Intelligence.StartPosition = FormStartPosition.CenterParent;
            xChip_Intelligence.ShowDialog();
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkEdit1.Checked)
            {
                SerialSend.WriteRegister(0x20000034, 0x1, sPortTemp);
                SerialSend.WriteRegister(0x20000037, 0x1, sPortTemp);
            }
            else
            {
                SerialSend.WriteRegister(0x20000034, 0x0, sPortTemp);
                SerialSend.WriteRegister(0x20000037, 0x0, sPortTemp);
            }
        }

        /// <summary>
        /// 打开adb 设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdb_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 刷新Adb 设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton20_Click(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// 开始监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void startMonitor_Click(object sender, EventArgs e)
        {
            //AdbLogcatManager.StartLogcat();
            //Task.Run(() =>
            //{
            //    foreach (var item in LogcatDataManager.GetAllData())
            //    {
            //        setShowMsg($"{item.RWText} 0x{item.RegAddr}:0x{item.Values}");
            //    }  
               
            //}
            
            //);
        }
        /// <summary>
        /// 停止监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void stopMonitor_Click(object sender, EventArgs e)
        {
            //AdbLogcatManager.StopCurrentLogcat();
        }
    }

}